Skip to content
All posts

React Hooks Deep Dive

Practical tips on useEffect, useLayoutEffect, useReducer, and useRef - their optimization patterns and common pitfalls.

Four coat hooks on a wooden rail holding tags for useState, useEffect, useRef and useReducer, above the words React Hooks, a deep dive

Hooks changed how we write React. They replaced lifecycle methods, made logic reusable, and pushed us toward functional components entirely. But with that power comes a set of subtle traps - stale closures, infinite loops, layout flickers - that can quietly break your app.

useEffect runs after paint, and its deps must be honest

useEffect runs after the browser has painted. That makes it the right place for data fetching, subscriptions, and side effects that don't need to block rendering.

jsx
useEffect(() => { fetchUser(userId).then(setUser); }, [userId]);

The dependency array controls when the effect re-runs. Missing a dependency means your effect works with stale data. Including too many causes unnecessary re-runs.

Pitfall: Stale Closures

jsx
// ❌ count is always 0 inside the interval useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, []); // ✅ use a ref or include count in deps useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]);

Always clean up subscriptions, timers, and event listeners in the return function - otherwise you'll leak memory and trigger state updates on unmounted components.

Pitfall: Infinite Loop

jsx
// ❌ object is recreated every render → effect loops forever const options = { page: 1 }; useEffect(() => { fetchData(options); }, [options]); // ✅ move stable values inside the effect or memoize them useEffect(() => { fetchData({ page: 1 }); }, []);

useLayoutEffect runs before paint: use it to measure

useLayoutEffect fires synchronously after DOM mutations but before the browser paints. Use it when you need to read layout or make DOM changes that would cause a visible flicker if deferred.

jsx
useLayoutEffect(() => { const rect = ref.current.getBoundingClientRect(); setTooltipPosition({ top: rect.bottom, left: rect.left }); }, []);

If you use useEffect here instead, the tooltip might render in the wrong position for one frame - a visible flash.

Rule of thumb: Start with useEffect. Switch to useLayoutEffect only if you notice a layout flicker.

Note that useLayoutEffect doesn't run on the server, which causes a mismatch warning in SSR apps. For SSR-safe code, guard it:

jsx
const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;

Try it: click each button a few times. With useEffect the tooltip flashes in the corner before it jumps under the button; with useLayoutEffect it appears in the right place straight away.

jsx
import { useEffect, useLayoutEffect, useRef, useState } from 'react'; import './styles.css'; // Pretend measuring is expensive, so the wrong frame stays on screen long enough to see. function slowDown(ms) { const end = performance.now() + ms; while (performance.now() < end) {} } function measure(anchorRef, setPosition) { slowDown(200); const rect = anchorRef.current.getBoundingClientRect(); setPosition({ top: rect.bottom + 8, left: rect.left }); } // Runs after the browser has painted: you may see the unmeasured tooltip first. function EffectTooltip({ anchorRef }) { const [position, setPosition] = useState(null); useEffect(() => measure(anchorRef, setPosition), [anchorRef]); return <Tooltip position={position} />; } // Runs before the browser paints: the first frame is already measured. function LayoutEffectTooltip({ anchorRef }) { const [position, setPosition] = useState(null); useLayoutEffect(() => measure(anchorRef, setPosition), [anchorRef]); return <Tooltip position={position} />; } function Tooltip({ position }) { return ( <div className={position ? 'tooltip' : 'tooltip unmeasured'} style={position ?? { top: 8, left: 8 }}> {position ? 'Right under the button' : 'Not measured yet!'} </div> ); } export default function App() { const anchorRef = useRef(null); const [shown, setShown] = useState(null); // Mount from a timer, like a tooltip that waits for data: React runs effects // caused by a click before paint, which would hide the difference. const show = (kind) => { setShown(null); setTimeout(() => setShown(kind)); }; return ( <main> <div className="buttons" ref={anchorRef}> <button onClick={() => show('effect')}>useEffect</button> <button onClick={() => show('layout')}>useLayoutEffect</button> </div> {shown === 'effect' && <EffectTooltip anchorRef={anchorRef} />} {shown === 'layout' && <LayoutEffectTooltip anchorRef={anchorRef} />} </main> ); }

useReducer turns tangled state into explicit transitions

When state logic grows complex - multiple sub-values, transitions that depend on the current state - useReducer is cleaner than stacking useState calls.

jsx
const initialState = { status: 'idle', data: null, error: null }; function reducer(state, action) { switch (action.type) { case 'FETCH_START': return { ...state, status: 'loading' }; case 'FETCH_SUCCESS': return { status: 'success', data: action.payload, error: null }; case 'FETCH_ERROR': return { status: 'error', data: null, error: action.payload }; default: return state; } } function UserProfile({ userId }) { const [state, dispatch] = useReducer(reducer, initialState); useEffect(() => { dispatch({ type: 'FETCH_START' }); fetchUser(userId) .then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data })) .catch(err => dispatch({ type: 'FETCH_ERROR', payload: err.message })); }, [userId]); if (state.status === 'loading') return <Spinner />; if (state.status === 'error') return <ErrorMessage message={state.error} />; return <Profile data={state.data} />; }

The reducer is a pure function - easy to test in isolation and reason about. All state transitions are explicit and centralized.

Optimization tip: dispatch from useReducer is stable across renders - you don't need to wrap it in useCallback.

useRef keeps values that shouldn't trigger a render

Everyone knows useRef for accessing DOM nodes. But its real power is storing any mutable value that persists across renders without triggering a re-render.

jsx
// Tracking previous value function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }, [value]); return ref.current; } function Counter() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); return ( <p>Now: {count}, Before: {prevCount}</p> ); }

Another common pattern - storing a timer ID or subscription so it survives re-renders:

jsx
const timerRef = useRef(null); const start = () => { timerRef.current = setInterval(tick, 1000); }; const stop = () => { clearInterval(timerRef.current); };

Pitfall: Reading ref.current inside JSX won't trigger a re-render when it changes. If you need the UI to update, use useState instead.

Custom hooks share logic, not state

Custom hooks are just functions that start with use and call other hooks. They're the right way to extract and share stateful logic.

jsx
function useFetch(url) { const [state, dispatch] = useReducer(reducer, initialState); useEffect(() => { if (!url) return; let cancelled = false; dispatch({ type: 'FETCH_START' }); fetch(url) .then(res => res.json()) .then(data => { if (!cancelled) dispatch({ type: 'FETCH_SUCCESS', payload: data }); }) .catch(err => { if (!cancelled) dispatch({ type: 'FETCH_ERROR', payload: err.message }); }); return () => { cancelled = true; }; }, [url]); return state; }

Notice the cancelled flag - it prevents setting state on an unmounted component when the URL changes before the previous fetch finishes.

The rules of hooks exist because React tracks hooks by call order

React tracks hooks by call order. That's why the rules matter:

  • Only call hooks at the top level - never inside conditions, loops, or nested functions
  • Only call hooks from React functions - components or custom hooks
jsx
// ❌ Breaks hook order on re-renders if (isLoggedIn) { const [profile, setProfile] = useState(null); } // ✅ Always called unconditionally const [profile, setProfile] = useState(null);

The ESLint plugin eslint-plugin-react-hooks catches these violations automatically - add it to your project if you haven't already.

Which hook for which job

  • Side effects after paint → useEffect with proper deps and cleanup
  • DOM reads before paint → useLayoutEffect
  • Complex state transitions → useReducer
  • Mutable values without re-renders → useRef
  • Reusable stateful logic → custom hooks
  • Avoiding violations → eslint-plugin-react-hooks