| |

React 131 ⚛️ The Complete Cheatsheet

⏱️ Estimated read: 7 min | |

1. Components & JSX

JSX is syntax sugar for React.createElement. Components are functions that return JSX.

// Functional Component
function Welcome({ name }) {
  return <h1>Hello, {name}</h1>;
}

// Arrow Function Component
const Button = ({ onClick, children }) => (
  <button onClick={onClick}>{children}</button>
);

// Fragment
<>
  <Header />
  <Main />
</>

// Keyed Fragment
<React.Fragment key={id}>
  <Row />
</React.Fragment>

// Conditional Rendering
{isLoggedIn && <AdminDashboard />}
{isLoggedIn ? <UserMenu /> : <LoginButton />}

// Lists
{items.map(item => (
  <li key={item.id}>{item.name}</li>
))}

2. useState

Manages state within a functional component.

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

setCount(1);
setCount(prev => prev + 1);
const [s, setS] = useState(() => init());

setUser(prev => ({ ...prev, name: 'Al' }));
setList(prev => [...prev, item]);
setList(prev => prev.filter(x => x.id !== id));
setList(prev => prev.map(x => x.id === id ? { ...x, done: true } : x));

3. useReducer

Manages complex state through a reducer function.

const [state, dispatch] = useReducer(reducer, initialState);
dispatch({ type: 'increment' });

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

4. useEffect

Handles side effects after render.

useEffect(() => {
  document.title = `Count: ${count}`;
  return () => { /* cleanup */ };
}, [count]);

useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);
}, []);

useEffect(() => {
  const sub = subscribe(userId, onChange);
  return () => sub.unsubscribe();
}, [userId]);

useEffect(() => {
  const c = new AbortController();
  fetch(url, { signal: c.signal }).then(r => r.json()).then(setData);
  return () => c.abort();
}, [url]);

5. useLayoutEffect

Runs synchronously before the browser paints.

useLayoutEffect(() => {
  const { height } = ref.current.getBoundingClientRect();
  setHeight(height);
}, []);

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

6. useRef

Holds a mutable value or DOM reference without re-rendering.

const inputRef = useRef(null);
inputRef.current.focus();
return <input ref={inputRef} />;

const countRef = useRef(0);
countRef.current += 1;

const prevRef = useRef(value);
useEffect(() => { prevRef.current = value; }, [value]);

7. useMemo & useCallback

Memoizes values and functions to avoid unnecessary recomputation.

const sorted = useMemo(() => items.sort(compare), [items]);
const handleSelect = useCallback((id) => select(id), [select]);

const Row = React.memo(({ item, onSelect }) => (
  <button onClick={() => onSelect(item.id)}>{item.name}</button>
));

8. useContext

Reads data from a React Context.

const ThemeContext = createContext('light');

<ThemeContext.Provider value="dark">
  <App />
</ThemeContext.Provider>

const theme = useContext(ThemeContext);

9. useId

Generates stable, unique IDs for accessibility attributes.

const id = useId();
<label htmlFor={id}>Name</label>
<input id={id} />

10. useTransition & useDeferredValue

Marks updates as non-urgent so the UI stays responsive.

const [isPending, start] = useTransition();
start(() => setQuery(input));

const deferred = useDeferredValue(query);
<Results query={deferred} />

11. useSyncExternalStore

Subscribes to an external store without tearing.

const value = useSyncExternalStore(
  subscribe,
  () => store.get(),
  () => store.getSSR()
);

12. Forms & Server Actions

Handles form state and server-side submission.

const [name, setName] = useState('');
<input value={name} onChange={e => setName(e.target.value)} />

const ref = useRef(null);
<input ref={ref} defaultValue="Al" />
ref.current.value;

new FormData(e.currentTarget).get('name');

const [state, action, pending] = useActionState(
  async (prev, fd) => {
    if (!fd.get('name')) return { error: 'Required' };
    await save(fd.get('name'));
    return { ok: true };
  },
  null
);

function Submit() {
  const { pending } = useFormStatus();
  return <button disabled={pending}>Save</button>;
}

13. useOptimistic

Shows an optimistic UI update before the server responds.

const [optimistic, addOptimistic] = useOptimistic(
  messages,
  (state, newMsg) => [...state, newMsg]
);

addOptimistic({ text, id: 'temp' });
await saveMessage(text);

14. use

Reads a promise or context during render.

const data = use(promise);
const theme = use(ThemeContext);

15. forwardRef & useImperativeHandle

Passes refs through components and exposes a custom ref API.

const Input = forwardRef((props, ref) => {
  const inner = useRef(null);
  useImperativeHandle(ref, () => ({
    focus: () => inner.current.focus(),
  }));
  return <input ref={inner} {...props} />;
});

const ref = useRef(null);
<Input ref={ref} />
ref.current.focus();

16. Suspense & Lazy

Loads components lazily with a fallback.

const Chart = lazy(() => import('./Chart'));

<Suspense fallback={<Spinner />}>
  <Chart />
</Suspense>

17. Error Boundary

Catches render errors in a component subtree.

class Boundary extends React.Component {
  state = { error: null };
  static getDerivedStateFromError(error) { return { error }; }
  componentDidCatch(error, info) { logError(error, info); }
  render() {
    if (this.state.error) return <Fallback error={this.state.error} />;
    return this.props.children;
  }
}

<Boundary><App /></Boundary>

18. Portals

Renders a child outside its parent DOM tree.

import { createPortal } from 'react-dom';
createPortal(<Modal />, document.body);

19. Context Pattern (Reducer + Two Contexts)

Separates state and dispatch contexts to avoid re-renders.

const StateContext    = createContext(null);
const DispatchContext = createContext(null);

function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, init);
  const value = useMemo(() => ({ state }), [state]);
  return (
    <StateContext.Provider value={value}>
      <DispatchContext.Provider value={dispatch}>
        {children}
      </DispatchContext.Provider>
    </StateContext.Provider>
  );
}

const { state }  = useContext(StateContext);
const dispatch   = useContext(DispatchContext);

20. Server Components

Renders on the server; ships no JS to the client.

async function Page() {
  const data = await fetch(url);
  return <Client data={data} />;
}

'use client';
export function Client({ data }) {
  const [open, setOpen] = useState(false);
  return <button onClick={() => setOpen(!open)} />;
}

21. Server Functions

Runs on the server when called from the client.

'use server';
export async function del(id) {
  const s = await getSession();
  if (!owns(s, id)) throw new Error('Unauthorized');
  await db.del(id);
}

22. Zustand

Minimal external state store with selectors.

const useStore = create(set => ({
  count: 0,
  inc: () => set(s => ({ count: s.count + 1 })),
}));

const count = useStore(s => s.count);
const inc   = useStore(s => s.inc);

23. TanStack Query

Manages server state: caching, refetching, and mutations.

const { data, isLoading, error } = useQuery({
  queryKey: ['user', id],
  queryFn: () => fetchUser(id),
  staleTime: 60_000,
});

const mut = useMutation({
  mutationFn: updateUser,
  onSuccess: () => qc.invalidateQueries(['user', id]),
});

mut.mutate({ name: 'Al' });

24. Testing

Renders components and queries them the way users would.

render(<Button onClick={fn}>Save</Button>);

const btn = screen.getByRole('button', { name: 'Save' });
await userEvent.click(btn);
expect(fn).toHaveBeenCalled();

await screen.findByText('Loaded');
await waitFor(() => expect(fn).toHaveBeenCalled());

25. Accessibility

Uses semantic HTML and ARIA attributes for screen readers and keyboard users.

<button aria-label="Close" onClick={close}>×</button>

<label htmlFor={id}>Name</label>
<input id={id} />

<div role="dialog" aria-modal="true" aria-labelledby={titleId}>

26. StrictMode

Surfaces side-effect bugs by double-invoking effects in development.

<React.StrictMode>
  <App />
</React.StrictMode>

27. Gotchas

Common mistakes and their fixes.

setCount(count + 1);                      // ❌ stale closure
setCount(prev => prev + 1);               // ✅

useEffect(fn, [{ id }]);                  // ❌ object dep
useEffect(fn, [id]);                      // ✅

useEffect(() => { setInterval(fn, 1000); }, []);          // ❌ leak
useEffect(() => { const id = setInterval(fn, 1000); return () => clearInterval(id); }, []); // ✅

items.map((x, i) => <Row key={i} />);     // ❌ index key
items.map(x => <Row key={x.id} />);       // ✅

<C.Provider value={{ user, setUser }}>    // ❌ new value each render
<C.Provider value={useMemo(() => ({ user, setUser }), [user])}> // ✅

useEffect(() => { fetch(url).then(setData); }, []);       // ❌
useQuery({ queryKey: ['user', id], queryFn: () => fetchUser(id) }); // ✅

useEffect(() => setTotal(items.reduce(...)), [items]);    // ❌ derived state
const total = items.reduce((a, b) => a + b.price, 0);     // ✅

<div onClick={fn}>Click</div>             // ❌ not keyboard accessible
<button onClick={fn}>Click</button>       // ✅

if (x) setX(1);                           // ❌ setState in render
const y = x ? 1 : 0;                      // ✅

react, hooks, cheatsheet, patterns

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!