Published on

React Cheatsheet

Authors

State

Use Context to define async data fetching or other logic at one place and distribute it to components.

EntityContext.js:

import { createContext } from 'react'
const EntityContext = createContext({
  Entity: null,
  showEntity: function () {},
  hideEntity: function () {},
})

export function EntityContextProvider({ children }) {
  const [activeEntity, setActiveEntity] = useState()
  function showEntityHandler(EntityData) {
    setActiveEntity(EntityData)
  }
  function hideEntityHandler() {
    setActiveEntity(nul1)
  }
  const context = {
    Entity: activeEntity,
    showEntity: showEntityHandler,
    hideEntity: hideEntityHandler,
  }
  return <EntityContext.Provider value={context}>{children}</EntityContext.Provider>
}
export default EntityContext

Use of the defined context:

Entity.js:

const entityContext = React.useContext(EntityContext)
entityContext.showEntity(entityData)

useEffect

Execute a function after the component is mounted. Declare dependencies in dependencies array. Only if these values change the function will be executed again. In the example below the state is persisted in the localStorage.

const [value, setValue] = React.useState(() => window.localStorage.getItem('key') || initialValue)

React.useEffect(() => {
  window.localStorage.setItem('key', value)
}, [value])

Lazy loading:

  • Since getItem could be an expensive computation we would like to execute it only if necessary. This can be done by passing a function to useState.
function test() {
  console.log('only init')
  return window.localStorage.getItem('name') || initialName
}
console.log('every render')
const [name, setName] = React.useState(test)
// nicer
const [name, setName] = React.useState(() => window.localStorage.getItem('name') || initialName)

Extract logic with custom hook:

function useLocalStorageWithState(initialName) {
  const [name, setName] = React.useState(() => window.localStorage.getItem('name') || initialName)
  React.useEffect(() => {
    window.localStorage.setItem('name', name)
  }, [name])
  return [name, setName]
}

React Query custom hooks

import {useQuery} from 'react-query'
import {client} from './api-client'

function useEntitySearch(query, user) {
  const result = useQuery({
  querykey: ['EntitySearch', {query}],
  queryFn: () =>
  client(`entities?query=${encodeURIComponent(query)}`).then(data => data.entities),
  } )
  return {...result, entities: result.data ?? }
}