React Hooks Cheat Sheet

React Hooks Cheat Sheet

Complete reference for core React Hooks, with examples and best practices — useState, useEffect, useContext, and custom hooks included.

8
Sections
40+
Examples
Core
Hooks Covered
Guides
Best Practices

State Management Hooks

Hooks for storing and updating component state.

Beginner
2 examples

useState React

Declare local state in a functional component.

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
    </div>
  );
}

useReducer React

Manage complex state logic or multiple sub-values.

import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}

Side Effects Hooks

Run side effects such as fetching, subscriptions, or manual DOM updates.

Beginner
3 examples

useEffect (Basic) React

Run effect after render. Cleanup with returned function.

import React, { useEffect } from 'react';

function Example() {
  useEffect(() => {
    console.log('Mounted or deps changed');

    return () => {
      console.log('Cleanup before unmount or deps change');
    };
  }, []); // empty deps => runs once on mount

  return <div>Check console</div>;
}

useEffect (Data Fetch) React

Fetch data and manage loading/error states.

import React, { useEffect, useState } from 'react';

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let mounted = true;
    fetch('/api/users')
      .then(res => res.json())
      .then(data => {
        if (mounted) {
          setUsers(data);
          setLoading(false);
        }
      })
      .catch(() => {
        if (mounted) setLoading(false);
      });
    return () => { mounted = false; }; // avoid state update after unmount
  }, []);

  if (loading) return <div>Loading...</div>;
  return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

useLayoutEffect React

Synchronous after DOM mutations — useful for measurements.

import React, { useRef, useLayoutEffect, useState } from 'react';

function Measure() {
  const ref = useRef();
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    if (ref.current) {
      setWidth(ref.current.getBoundingClientRect().width);
    }
  }, []);

  return (
    <div>
      <div ref={ref}>Measure me</div>
      <p>Width: {width}px</p>
    </div>
  );
}

Context Hooks

Share values across the component tree without prop drilling.

Beginner
1 examples

useContext React

Consume a React Context value inside a functional component.

import React, { createContext, useContext } from 'react';

const ThemeContext = createContext({ bg: '#fff', color: '#000' });

function ThemedBox() {
  const theme = useContext(ThemeContext);
  return <div style={{ background: theme.bg, color: theme.color }}>Themed box</div>;
}

function App() {
  return (
    <ThemeContext.Provider value={{ bg: '#111', color: '#fff' }}>
      <ThemedBox />
    </ThemeContext.Provider>
  );
}

Performance & Memoization

Avoid unnecessary renders and expensive recalculations.

Intermediate
2 examples

useMemo React

Memoize expensive computations between renders.

import React, { useMemo } from 'react';

function Expensive({ items }) {
  const total = useMemo(() => {
    // heavy calculation
    return items.reduce((s, i) => s + i.value, 0);
  }, [items]);

  return <div>Total: {total}</div>;
}

useCallback React

Memoize callbacks to avoid re-creating functions each render.

import React, { useCallback, useState } from 'react';

function Parent() {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount(c => c + 1);
  }, []); // stable reference

  return <Child onClick={handleClick} />;
}

function Child({ onClick }) {
  return <button onClick={onClick}>Click</button>;
}

Refs & Imperative APIs

Access DOM nodes or expose imperative methods from child components.

Intermediate
2 examples

useRef React

Hold mutable value or reference to DOM node.

import React, { useRef } from 'react';

function FocusInput() {
  const inputRef = useRef(null);

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current?.focus()}>Focus</button>
    </div>
  );
}

useImperativeHandle React

Customize instance value when using forwardRef.

import React, { forwardRef, useImperativeHandle, useRef } from 'react';

const FancyInput = forwardRef((props, ref) => {
  const inputRef = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => inputRef.current?.focus(),
    clear: () => { inputRef.current.value = ''; }
  }));
  return <input ref={inputRef} />;
});

function Parent() {
  const ref = React.useRef();
  return (
    <div>
      <FancyInput ref={ref} />
      <button onClick={() => ref.current?.focus()}>Focus from parent</button>
    </div>
  );
}

IDs & Dev Helpers

Utilities for stable ids and debugging.

Intermediate
2 examples

useId React

Generate stable unique IDs for accessibility.

import React, { useId } from 'react';

function Checkbox({ label }) {
  const id = useId();
  return (
    <div>
      <input id={id} type="checkbox" />
      <label htmlFor={id}>{label}</label>
    </div>
  );
}

useDebugValue React

Show debug info for custom hooks in React DevTools.

import { useDebugValue, useState, useEffect } from 'react';

function useFriendStatus(friendId) {
  const [status, setStatus] = useState(null);
  useEffect(() => {
    // subscribe to friend status...
  }, [friendId]);
  useDebugValue(status ? 'online' : 'offline');
  return status;
}

Custom Hooks

Encapsulate reusable logic into custom hooks.

Intermediate
2 examples

useToggle React

Simple boolean toggle hook.

import { useState, useCallback } from 'react';

function useToggle(initial = false) {
  const [on, setOn] = useState(initial);
  const toggle = useCallback(() => setOn(v => !v), []);
  return [on, toggle];
}

// Usage
function Example() {
  const [on, toggle] = useToggle();
  return <button onClick={toggle}>{on ? 'ON' : 'OFF'}</button>;
}

useFetch (basic) React

Reusable data fetching hook with loading & error states.

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    fetch(url)
      .then(r => r.json())
      .then(json => {
        if (mounted) {
          setData(json);
          setLoading(false);
        }
      })
      .catch(err => {
        if (mounted) {
          setError(err);
          setLoading(false);
        }
      });
    return () => { mounted = false; };
  }, [url]);

  return { data, loading, error };
}

// Usage
function Users() {
  const { data, loading } = useFetch('/api/users');
  if (loading) return <div>Loading...</div>;
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

Best Practices

Guidelines for writing reliable and performant hooks.

Expert
2 examples

Rules of Hooks React

Always call hooks at the top level and only from React functions.

// ✅ Correct
function MyComponent() {
  useState();
  useEffect();
}

// ❌ Incorrect
if (condition) {
  useState(); // don't call inside conditionals
}

Performance Tips React

Avoid unnecessary re-renders and stale closures.

// Use dependencies correctly
useEffect(() => { /* ... */ }, [dep1, dep2]);

// Use useCallback/useMemo for stable references
const memoized = useMemo(() => compute(x), [x]);
const stableFn = useCallback(() => doThing(a), [a]);

React Hooks Best Practices & Tips

Practical guidelines to avoid common pitfalls and write maintainable hooks.

Stability

  • Always declare hooks at the top level of your components.
  • Provide correct dependency arrays to avoid stale closures.
  • Use useCallback/useMemo when passing props to memoized children.

Safety

  • Avoid setting state on unmounted components — cancel async work in cleanup.
  • Prefer functional updates when new state depends on previous state.
  • Keep side-effects isolated and predictable.

Design

  • Extract reusable logic into custom hooks (start with useX naming).
  • Keep hooks focused — single responsibility makes them easier to test.
  • Document required inputs and returned values for each custom hook.
Buy Me A Coffee