React hooks

react-hooks

General

useState

useState provides a value that will persist across renders and an API to update that value and trigger a re-render.

Functional Updates

Use whenever you set the current state based on the previous state.

const increment = () => setCount((count) => count + 1)

Lazy State Initialization

Use if the initial value for state is the result of an expensive calculation.

const [count, setCount] = React.useState(() => getExpensiveCount())

useEffect

The effect runs AFTER React updates the DOM and AFTER the browser paints those updates.

Cleanup function

Invoked right before invoking the new effect on a re-render AND right before removing the component from the DOM.

React.useEffect(() => {
  return function cleanup() { ... }
})

useLayoutEffect

The effect runs AFTER React updates the DOM and BEFORE the browser paints those updates.

Updates scheduled inside useLayoutEffect are flushed synchronously, so prefer the standard useEffect when possible to avoid blocking visual updates.

useReducer

useReducer offers more flexibility (over useState) since it allows you to decouple how the state is updated from the action that triggered the update - typically leading to more declarative state updates.

useReducer should be used if updating one piece of state is based on another piece of state.

useRef

Allows to persist a value across renders without causing a re-render.

useCallback

Returns a function whose reference will persist across renders.

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

References

< back to index