Skip to content

React Hooks Explained: useState, useEffect, useRef and More

Hooks are the functions whose names start with use, like useState and useEffect. You call them at the top of a function component, and they give it things a plain function doesn’t have: a value that survives between renders (useState), code that runs after the page updates (useEffect), a handle on a real element (useRef), and a few more.

A first hook: a counter

Here’s the hook you’ll write most often. It keeps a number, and the button changes it:

CoffeeCounter.jsx
import { useState } from 'react';export default function CoffeeCounter() {  const [cups, setCups] = useState(0);  return (    <div>      <p>Coffees today: {cups}</p>      <button onClick={() => setCups(cups + 1)}>Add one</button>    </div>  );}
Open in React Playground
HTML from CoffeeCounter

useState(0) hands back two things: the current value (cups, 0 to start) and a function that changes it (setCups). Click the button and setCups(cups + 1) tells React the value changed, so React calls CoffeeCounter again, this time with cups set to 1, and updates the page to match. That second call is a re-render.

The white box is stuck at 0: it’s the HTML from that very first render, and nothing runs in it. Open the playground link and press Run to click the real button. Every complete example on this page has a link like it.

The hooks you’ll use most

HookUse it toLooks like
useStateKeep a value that changes what’s on screenconst [cups, setCups] = useState(0);
useEffectTalk to things outside React: timers, fetch, the documentuseEffect(() => { … }, [day]);
useRefHold an element, or a value that shouldn’t redraw anythingconst inputRef = useRef(null);
useMemoKeep the result of a slow calculationuseMemo(() => filter(orders), [orders])
useCallbackKeep the same function from one render to the nextuseCallback(() => setName(''), [])
useContextRead a value a parent shares with everything below itconst theme = useContext(ThemeContext);

React has more (useReducer, useId, useTransition, useActionState for forms and others), but these six cover most components you’ll read or write. They all come from the react package: import { useState, useEffect } from 'react';

useState: remember a value

Why not just use a normal variable? Try it. This counter uses let, and it looks like it should work:

BrokenCounter.jsx (doesn’t update)
export default function BrokenCounter() {  let cups = 0;  function addOne() {    cups = cups + 1;    console.log('cups is now', cups);  }  return <button onClick={addOne}>Coffees today: {cups}</button>;}
Open in React Playground

Run it and click a few times. The console says 1, 2, 3, but the button keeps saying 0. Two things go wrong. Changing a plain variable doesn’t tell React anything, so nothing is redrawn. And even if something else caused a re-render, let cups = 0 would run again and start from zero. useState fixes both: React stores the value outside your function, hands it back on every render, and redraws when you call the setter.

One thing surprises almost everyone the first week. The setter doesn’t change the variable you’re holding right now. After setCups(5), a console.log(cups) on the next line still prints the old number. The new value arrives on the next render.

Objects and arrays in state

State can hold an object. To change one field, make a new object with the rest copied in:

CoffeeOrder.jsx
import { useState } from 'react';export default function CoffeeOrder() {  const [order, setOrder] = useState({ size: 'medium', milk: 'oat' });  return (    <div>      <p>        A {order.size} latte with {order.milk} milk      </p>      <button onClick={() => setOrder({ ...order, size: 'large' })}>Make it large</button>      <button onClick={() => setOrder({ ...order, milk: 'whole' })}>Whole milk</button>    </div>  );}
Open in React Playground
HTML from CoffeeOrder

{ ...order, size: 'large' } copies every field of order, then sets size. Why not write order.size = 'large' and pass order back? Because it’s the same object as before, React compares the old and new value, sees no change and skips the update. Always hand the setter something new.

Arrays work the same way. Instead of push or splice, build a new array:

ShoppingList.jsx
import { useState } from 'react';export default function ShoppingList() {  const [items, setItems] = useState([    { id: 1, name: 'Oat milk' },    { id: 2, name: 'Coffee beans' },  ]);  const [text, setText] = useState('');  function add() {    if (!text.trim()) return;    setItems([...items, { id: Date.now(), name: text.trim() }]);    setText('');  }  function remove(id) {    setItems(items.filter((item) => item.id !== id));  }  return (    <div>      <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Add an item" />      <button onClick={add}>Add</button>      <ul>        {items.map((item) => (          <li key={item.id}>            {item.name} <button onClick={() => remove(item.id)}>Remove</button>          </li>        ))}      </ul>    </div>  );}
Open in React Playground
ToWriteNot
Add an itemsetItems([...items, newItem])items.push(newItem)
Remove onesetItems(items.filter((i) => i.id !== id))items.splice(index, 1)
Change onesetItems(items.map((i) => (i.id === id ? { ...i, name } : i)))items[0].name = name
SortsetItems([...items].sort(byName))items.sort(byName)

Updating from the old value

This tip jar has two buttons that both call the setter three times. Only one of them adds 3:

TipJar.jsx
import { useState } from 'react';export default function TipJar() {  const [coins, setCoins] = useState(0);  function addThreeWrong() {    setCoins(coins + 1);    setCoins(coins + 1);    setCoins(coins + 1);  }  function addThree() {    setCoins((c) => c + 1);    setCoins((c) => c + 1);    setCoins((c) => c + 1);  }  return (    <div>      <p>Coins in the tip jar: {coins}</p>      <button onClick={addThreeWrong}>Add 3 (adds 1)</button>      <button onClick={addThree}>Add 3 (works)</button>    </div>  );}
Open in React Playground

In addThreeWrong, coins is 0 for the whole click, so it asks for “0 + 1” three times and you get 1. Passing a function, setCoins((c) => c + 1), tells React “take whatever the latest value is and add one”. React runs the three in a queue, so 0 becomes 1, then 2, then 3. Use this form whenever the new value depends on the old one, and always inside timers and effects, where the variable you captured can be long out of date.

useEffect: run code after render

Rendering should only work out what the page looks like. Anything that reaches outside React, like starting a timer, fetching data or changing document.title, goes in an effect. React runs it after the page has been updated:

TimeOnPage.jsx
import { useEffect, useState } from 'react';export default function TimeOnPage() {  const [seconds, setSeconds] = useState(0);  useEffect(() => {    const id = setInterval(() => {      setSeconds((s) => s + 1);    }, 1000);    return () => clearInterval(id);  }, []);  return <p>You have been here for {seconds} seconds.</p>;}
Open in React Playground

The function you pass is the setup: it starts a timer. The function it returns is the cleanup: React calls it when the component leaves the page, so the timer doesn’t keep ticking for a component nobody can see. Forget the cleanup and every visit to this screen adds another timer. Notice the (s) => s + 1: the effect runs once, so the seconds it captured stays 0 forever, and only the function form sees the real value.

The dependency array

The array at the end says when the effect runs again. List every value from the component that the effect reads:

You writeThe effect runs
useEffect(() => { … })After every render
useEffect(() => { … }, [])Once, after the first render (cleanup when the component goes)
useEffect(() => { … }, [note])After the first render, then whenever note changes
OrderNote.jsx
import { useEffect, useState } from 'react';export default function OrderNote() {  const [note, setNote] = useState('');  const [cups, setCups] = useState(1);  useEffect(() => {    console.log('Saving the note:', note);  }, [note]);  return (    <div>      <textarea value={note} onChange={(e) => setNote(e.target.value)} placeholder="Notes for the barista" />      <p>        <button onClick={() => setCups(cups + 1)}>Cups: {cups}</button>      </p>    </div>  );}
Open in React Playground

Run it and type a note: the console logs on every key, because note changed. Click the Cups button and nothing is logged. The component re-rendered, but note is the same, so React skipped the effect. When a value changes, React runs the old effect’s cleanup (if there is one) before the new setup.

Why does useEffect run twice?

If your app is rendered inside <StrictMode> (new React projects do this in main.jsx), React runs each new effect’s setup, then its cleanup, then the setup again, while you develop. It does that on purpose, to show you effects that are missing a cleanup. A production build runs it once. This clock starts up the same way a new project does, and logs both steps:

main.jsx
import { StrictMode, useEffect, useState } from 'react';import { createRoot } from 'react-dom/client';function Clock() {  const [time, setTime] = useState(() => new Date().toLocaleTimeString());  useEffect(() => {    console.log('Clock started');    const id = setInterval(() => setTime(new Date().toLocaleTimeString()), 1000);    return () => {      console.log('Clock stopped');      clearInterval(id);    };  }, []);  return <p>The time is {time}</p>;}function App() {  const [show, setShow] = useState(true);  return (    <div>      <button onClick={() => setShow(!show)}>{show ? 'Hide' : 'Show'} the clock</button>      {show && <Clock />}    </div>  );}// The same start-up code a new React project has in main.jsx.createRoot(document.getElementById('root')).render(  <StrictMode>    <App />  </StrictMode>);
Open in React Playground

Run it and look at the console: “Clock started”, “Clock stopped”, “Clock started”. Hide the clock and you get one more “Clock stopped”; show it again and the start, stop, start pattern repeats, because that’s a fresh clock. With a good cleanup the double run is harmless, and you’d never see it on screen. If it causes a bug, like two chat connections or a doubled analytics event, the effect is missing a cleanup. Don’t remove StrictMode to hide it.

Strict Mode also calls your component function twice per render while you develop. That’s why a console.log in the body of a component can show up twice in the browser console.

Fetching data in an effect

Loading data when a value changes is a common job for an effect, and it hides a race. If the person switches days quickly, two requests are on their way, and the slow one can land last and overwrite the right answer. An ignore flag fixes it. This demo uses a pretend server, so it runs anywhere:

DailySpecial.jsx
import { useEffect, useState } from 'react';// Pretends to be a server. Monday's answer takes 2 seconds, the others are quick.function getSpecial(day) {  const specials = { Monday: 'Maple latte', Tuesday: 'Iced mocha', Wednesday: 'Chai' };  const wait = day === 'Monday' ? 2000 : 300;  return new Promise((resolve) => setTimeout(() => resolve(specials[day]), wait));}export default function DailySpecial() {  const [day, setDay] = useState('Tuesday');  const [special, setSpecial] = useState(null);  useEffect(() => {    let ignore = false;    setSpecial(null);    getSpecial(day).then((result) => {      if (!ignore) setSpecial(result);    });    return () => {      ignore = true;    };  }, [day]);  return (    <div>      {['Monday', 'Tuesday', 'Wednesday'].map((d) => (        <button key={d} onClick={() => setDay(d)} disabled={d === day}>          {d}        </button>      ))}      <p>{special ? `${day}: ${special}` : 'Loading...'}</p>    </div>  );}
Open in React Playground

Click Monday, then Wednesday straight away. Monday’s answer takes 2 seconds, so it arrives last. By then the effect for Monday has been cleaned up, ignore is true for that request, and the late “Maple latte” is thrown away. Delete if (!ignore) in the playground and try again: the page ends up saying “Wednesday: Maple latte”. Here’s the same pattern with a real fetch and an error message:

Menu.jsx (needs your own server at /api/menu)
import { useEffect, useState } from 'react';export default function Menu({ day }) {  const [menu, setMenu] = useState(null);  const [error, setError] = useState('');  useEffect(() => {    let ignore = false;    setMenu(null);    setError('');    fetch(`/api/menu?day=${day}`)      .then((res) => {        if (!res.ok) throw new Error('The menu could not be loaded');        return res.json();      })      .then((data) => {        if (!ignore) setMenu(data);      })      .catch((err) => {        if (!ignore) setError(err.message);      });    return () => {      ignore = true;    };  }, [day]);  if (error) return <p>{error}</p>;  if (!menu) return <p>Loading...</p>;  return (    <ul>      {menu.map((item) => (        <li key={item.id}>{item.name}</li>      ))}    </ul>  );}

It works, but it’s a lot of code for every screen. That’s why bigger apps usually load data through their framework (Next.js, React Router) or a data library such as TanStack Query, which handle caching and these races for you. And if a value can be worked out from props or state, like a total price, work it out during render. It doesn’t need an effect or its own state at all.

useRef: elements and quiet values

useRef gives you a small box, { current: … }, that stays the same object for the life of the component. The most common use is getting hold of a real element, for example to put the cursor in a box:

CupName.jsx
import { useRef } from 'react';export default function CupName() {  const inputRef = useRef(null);  return (    <div>      <input ref={inputRef} placeholder="Name for the cup" />      <button onClick={() => inputRef.current.focus()}>Write a name</button>    </div>  );}
Open in React Playground

ref={inputRef} tells React to put the <input> element into inputRef.current once it’s on the page, so the button can call the browser’s own .focus(). The second use is a value you need to keep but that shouldn’t redraw anything when it changes, like a timer id:

BrewTimer.jsx
import { useRef, useState } from 'react';export default function BrewTimer() {  const [seconds, setSeconds] = useState(0);  const intervalRef = useRef(null);  function start() {    if (intervalRef.current) return; // already running    intervalRef.current = setInterval(() => setSeconds((s) => s + 1), 1000);  }  function stop() {    clearInterval(intervalRef.current);    intervalRef.current = null;  }  return (    <div>      <p>Brewing for {seconds}s</p>      <button onClick={start}>Start</button>      <button onClick={stop}>Stop</button>    </div>  );}
Open in React Playground

The interval id lives in a ref, because nothing on screen shows it. Changing intervalRef.current doesn’t cause a re-render, and it’s not reset when one happens. The rule of thumb: if the page shows it, use state; if only your event handlers need it, a ref will do. Don’t read or change ref.current while rendering (in the body of the component); do it in event handlers and effects.

useMemo and useCallback: when they help, and when they don’t

Every render runs your whole component function again. Usually that’s cheap. useMemo is for the rare part that isn’t: it keeps the result and only works it out again when its dependencies change.

OrderSearch.jsx
import { useMemo, useState } from 'react';// 5,000 made-up orders, so the filter has some work to do.const orders = Array.from({ length: 5000 }, (_, i) => ({  id: i + 1,  drink: ['Latte', 'Mocha', 'Flat white', 'Chai'][i % 4],  name: ['Sam', 'Priya', 'Alex', 'Mei', 'Omar'][i % 5],}));export default function OrderSearch() {  const [query, setQuery] = useState('');  const [big, setBig] = useState(false);  const matches = useMemo(() => {    console.log('Filtering for', JSON.stringify(query));    const q = query.toLowerCase();    return orders.filter((o) => o.drink.toLowerCase().includes(q) || o.name.toLowerCase().includes(q));  }, [query]);  return (    <div style={{ fontSize: big ? 22 : 16 }}>      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search orders" />      <button onClick={() => setBig(!big)}>Bigger text</button>      <p>{matches.length} orders match</p>    </div>  );}
Open in React Playground

Type in the search box and the console logs “Filtering for …” on each key. Click “Bigger text”: the component re-renders, but query didn’t change, so the filter is skipped and nothing is logged. Mind you, a filter over 5,000 short items is quick even without useMemo. It earns its place when the work is really slow (time it with console.time() first), or when another hook or a memoized child needs the same array object from one render to the next.

useCallback is the same idea for a function. Each render creates new functions, which is fine until you pass one to a child wrapped in memo(). memo skips redrawing the child when its props haven’t changed, and a new function counts as a change:

CupLabel.jsx
import { memo, useCallback, useState } from 'react';const ClearButton = memo(function ClearButton({ onClear }) {  console.log('ClearButton drew');  return <button onClick={onClear}>Clear</button>;});export default function CupLabel() {  const [name, setName] = useState('');  const clear = useCallback(() => setName(''), []);  return (    <div>      <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Name for the cup" />      <ClearButton onClear={clear} />      <p>Cup for: {name || 'nobody yet'}</p>    </div>  );}
Open in React Playground

Type a name: the console says “ClearButton drew” only once, at the start, because clear is the same function every time. Change the line to const clear = () => setName(''); and the button redraws on every key. Without memo() on the child, useCallback does nothing useful at all. Both hooks are about speed, never about whether the code works, so add them when something is actually slow. If your project uses the React Compiler, it adds this kind of caching for you.

useContext: skip the prop chain

Passing a value through five layers of components that don’t use it gets old fast. Context lets a parent share a value with everything below it, and any component can read it with useContext:

ThemeSwitch.jsx
import { createContext, useContext, useState } from 'react';const ThemeContext = createContext('light');function SpecialCard() {  const theme = useContext(ThemeContext);  return <p className={'card ' + theme}>Today: pumpkin spice latte ({theme} theme)</p>;}export default function App() {  const [theme, setTheme] = useState('light');  return (    <ThemeContext value={theme}>      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>Switch theme</button>      <SpecialCard />    </ThemeContext>  );}
Open in React Playground
HTML from App

createContext('light') makes the context with a default value. <ThemeContext value={theme}> shares the current theme with everything inside it, and SpecialCard reads it without any props. When the value changes, every component that reads it re-renders. That’s React 19’s way to write it. Older code uses <ThemeContext.Provider value=…>, which still works.

Your own hook: useLocalStorage

A custom hook is a normal function whose name starts with use and that calls other hooks. It’s how you reuse stateful logic between components. This one works like useState, but remembers the value in the browser’s local storage:

useLocalStorage.jsx
import { useEffect, useState } from 'react';function useLocalStorage(key, initialValue) {  const [value, setValue] = useState(() => {    try {      const saved = localStorage.getItem(key);      return saved !== null ? JSON.parse(saved) : initialValue;    } catch {      return initialValue; // storage blocked, or not valid JSON    }  });  useEffect(() => {    try {      localStorage.setItem(key, JSON.stringify(value));    } catch {      // storage is full or blocked (some private windows do this)    }  }, [key, value]);  return [value, setValue];}export default function CupName() {  const [name, setName] = useLocalStorage('cup-name', 'Sam');  return (    <label>      Name on your cup{' '}      <input value={name} onChange={(e) => setName(e.target.value)} />    </label>  );}
Open in React Playground

Two details are worth copying. useState(() => …) with a function reads storage only on the first render, not on every one. And both storage calls are wrapped in try, because local storage can be blocked or full, and a crash there would take the whole component with it. The playground’s preview is one of the places where storage is blocked, so the name won’t survive a reload there. In your own project it will.

Each component that calls useLocalStorage gets its own state. A custom hook shares the logic, not the value. To share one value between components, lift the state up to a parent or use context.

The rules of hooks

React tells hooks apart by the order you call them in, so that order has to be the same on every render. That gives two rules:

  • Call hooks at the top level of your component. Not inside an if, a loop, a nested function or after an early return.
  • Call them only from components or your own hooks. Not from plain helper functions, event handlers or class components.
Breaks the rules: a hook in an if
import { useState } from 'react';export default function Receipt() {  const [isMember, setIsMember] = useState(false);  if (isMember) {    const [points] = useState(120); // a hook inside an if: breaks the rules    console.log('Points:', points);  }  const [cups] = useState(2);  return (    <div>      <p>{cups} coffees{isMember && ', member price'}</p>      <button onClick={() => setIsMember(true)}>I am a member</button>    </div>  );}
Open in React Playground
Fixed: every hook, every time
import { useState } from 'react';export default function Receipt() {  const [isMember, setIsMember] = useState(false);  const [points] = useState(120);  const [cups] = useState(2);  return (    <div>      <p>{cups} coffees{isMember && ', member price'}</p>      {isMember && <p>You have {points} points.</p>}      <button onClick={() => setIsMember(true)}>I am a member</button>    </div>  );}
Open in React Playground

Run the first one and click the button. The second render calls one more hook than the first: React warns that the order of hooks changed, then stops with an error. These are the messages you’ll meet, and what usually causes them:

  • “Rendered more hooks than during the previous render.” A hook inside an if that just became true, like the example above. React also warns “React has detected a change in the order of Hooks”.
  • “Rendered fewer hooks than expected. This may be caused by an accidental early return statement.” The opposite: a return or condition skipped a hook this time.
  • “Invalid hook call. Hooks can only be called inside of the body of a function component.” A hook in an event handler, a plain function or a class. It also shows up when a project ends up with two copies of React.

You don’t have to spot these by eye. The eslint-plugin-react-hooks lint rules underline a broken rule and a missing dependency while you type, and most React starters switch them on.

Common mistakes

  • Calling the setter while rendering. onClick={setCups(0)} calls setCups during render, which causes a render, which calls it again. React stops with “Too many re-renders”. Write onClick={() => setCups(0)}.
  • An effect that sets its own trigger. An effect with no dependency array that sets state runs after every render and causes another one. The number races up for as long as the page is open, and the console fills with “Maximum update depth exceeded”:
Basket.jsx (loops forever on purpose)
import { useEffect, useState } from 'react';export default function Basket() {  const [count, setCount] = useState(0);  useEffect(() => {    setCount(count + 1); // runs after every render, and causes another render  });  return <p>Items: {count}</p>;}
  • A missing dependency. If an effect reads day but the array is [], it keeps using the first day forever. List what it reads; the lint rule will tell you.
  • Changing state in place. items.push(x) followed by setItems(items) changes nothing on screen. Pass a new array or object.
  • Expecting the new value right away. After setCups(5) the cups variable is still the old number until the next render. If you need the new value straight away, keep it in a local variable too.
  • An effect for a value you can work out. useEffect(() => setTotal(price * cups), [price, cups]) draws the page twice. const total = price * cups; in the component body does the same job in one go.

Questions people ask

What are React hooks?

Hooks are functions whose names start with use, such as useState, useEffect and useRef. You call them at the top of a function component to give it memory between renders, code that runs after the page updates, or a handle on a real element. For example, const [cups, setCups] = useState(0) keeps a number that survives re-renders.

What is the difference between useState and useRef?

Both keep a value between renders. Changing state with its setter makes React re-render the component, so use it for anything the page shows. Changing ref.current does not re-render anything, so use a ref for values only your handlers need, like a timer id, or for a DOM element you want to focus.

Why does useEffect run twice?

In development, when your app is wrapped in <StrictMode>, React runs each new effect setup, then its cleanup, then the setup again. It does that on purpose to show effects that are missing a cleanup. A production build runs it once. If the double run causes a bug, add a cleanup function instead of removing StrictMode.

What does the dependency array in useEffect do?

It says when the effect runs again. With no array it runs after every render. With [] it runs once after the first render. With [day] it runs after the first render and again whenever day changes. List every value from the component that the effect reads.

When should I use useMemo and useCallback?

Only when something is actually slow. useMemo keeps the result of a calculation until its dependencies change, which helps for heavy work. useCallback keeps the same function between renders, which only matters when you pass it to a child wrapped in memo() or list it in another hook’s dependencies. Neither changes what your code does, only how often work is repeated.

What are the rules of hooks?

Call hooks at the top level of a function component or a custom hook, in the same order on every render. Never call them inside an if, a loop, a nested function, after an early return, or from a plain function or class. Breaking the rule gives errors like “Rendered more hooks than during the previous render.”

How do I make a custom hook?

Write a function whose name starts with use and call other hooks inside it, then return whatever the component needs. A useLocalStorage(key, initialValue) hook, for example, wraps useState and useEffect and returns [value, setValue]. Each component that calls it gets its own copy of the state.

Why doesn’t my state update right away?

A setter asks React for a re-render with the new value; it does not change the variable you are holding. After setCups(5), cups is still the old number until the next render. If the new value depends on the old one, pass a function: setCups((c) => c + 1).

Can I use hooks in class components?

No. Hooks only work in function components and in custom hooks. A class component uses this.state and lifecycle methods instead. You can mix both kinds in one app, and a class component can render function components that use hooks.

Tools that help