React Hooks You Actually Need: A Practical Guide

React Hooks, introduced in 2019, have become the standard way to write React components. The API has over a dozen hooks but daily development requires familiarity with fewer than six. Here is the practical guide.

useState

The fundamental hook for local component state. const [value, setValue] = useState(initialValue). Call setValue to update the state; React re-renders the component. Prefer multiple useState calls over a single object state for unrelated values — it’s easier to reason about and more performant. For complex state transitions, useReducer is better than nested state updates via useState.

useEffect

Runs a side effect after every render (default), or only when specific dependencies change (pass a dependency array). Common uses: fetching data on component mount, setting up subscriptions, manually manipulating the DOM. The cleanup function (return () => cleanup()) runs when the component unmounts or before the next effect run. Missing dependencies in the dependency array is the most common source of subtle bugs in React code.

useContext

Reads the value from a Context Provider up the component tree. Replaces prop drilling (passing props through multiple component layers). Create a context with createContext, wrap your app or subtree with a Provider, consume with useContext anywhere inside. Performance caveat: every component consuming a context re-renders when the context value changes — use separate contexts for values that change at different frequencies.

useRef

Two main uses: holding a mutable value that does not trigger re-renders (useful for tracking previous values, storing timeouts), and accessing DOM elements directly (const inputRef = useRef(); pass inputRef to ref prop; access via inputRef.current). Unlike state, changing a ref does not re-render the component.

useMemo and useCallback

Optimisation hooks that memoize values and functions respectively to avoid unnecessary recalculations. Use useMemo when a calculation is genuinely expensive (filtering/sorting large arrays). Use useCallback when a stable function reference is needed (for passing to optimised child components or dependencies of other hooks). Don’t reach for these prematurely — React is fast by default; only optimise when you measure a performance problem.

上一篇 德国公共交通不只是火车:公共汽车、有轨电车和自行车
下一篇 你真正需要的React Hooks:实用指南