Skip to content
Happy Programming Guide
Start learning
JavaScript

React Hooks Explained for Beginners

Hooks let function components hold state and respond to changes. useState and useEffect with working examples, the rules that trip everyone, and the hooks you will actually use.

A pen and an open notebook ready for notes

Hooks are functions that give a React component abilities it would not otherwise have: remembering a value between renders, running code when something changes, reaching into shared data. There are only two you need to start, useState and useEffect, and a handful more you will meet within weeks. This article explains what each one does, shows working examples, and covers the two rules whose violation causes nearly every hooks bug.

Why hooks exist#

A React component is a function that returns what to show. React calls it every time it needs to update the screen. A plain function forgets everything between calls, so on its own a component cannot remember that a button was clicked. Hooks are how React lets the function keep things across calls: state that persists, effects that run when something changes.

useState#

JSX
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);      // current value, and a function to change it

  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

useState(0) gives a pair: the value now, and a setter. Calling the setter with a new value tells React to re-render the component; on that render, useState returns the new value. That loop — event, setter, re-render — is most of React.

Two things people learn the hard way:

JSX
setCount(count + 1);
setCount(count + 1);          // still only +1: both read the same old count

setCount(c => c + 1);
setCount(c => c + 1);         // +2: each update sees the latest value
JSX
const [items, setItems] = useState([]);
items.push('new');             // mutates; React does not notice
setItems([...items, 'new']);   // new array; React re-renders

Use the function form when the new value depends on the old, and always produce a new array or object rather than changing the existing one.

useEffect#

An effect is code that runs after React has updated the screen: fetching data, setting a title, subscribing to something. It is for reaching outside the component.

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

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    let cancelled = false;
    fetch('/api/users/' + userId)
      .then(r => r.json())
      .then(data => { if (!cancelled) setUser(data); });
    return () => { cancelled = true; };       // cleanup: runs before the next effect, and on unmount
  }, [userId]);                               // re-run only when userId changes

  if (!user) return <p>Loading…</p>;
  return <h1>{user.name}</h1>;
}

The second argument, the dependency array, controls when the effect runs:

Dependencies Runs
Omitted After every render. Rarely what you want.
[] Once, after the first render.
[userId] After the first render, and again whenever userId changes.

The cleanup function matters for anything that could still be in flight when the component changes or disappears: a fetch that would set state on an unmounted component, a timer, a subscription. Return a function that undoes the effect.

The rules of hooks#

  1. Call hooks at the top level of the component, never inside a condition, a loop, or a nested function. React tracks hooks by the order they are called, so the order must be identical every render.
  2. Call hooks only from React function components or from other hooks. Not from plain functions, not from class components.
JSX
function Bad({ show }) {
  if (show) {
    const [x, setX] = useState(0);     // breaks rule 1: order changes when show changes
  }
}

function Good({ show }) {
  const [x, setX] = useState(0);       // always called
  if (!show) return null;
}

The error Rendered more hooks than during the previous render is rule 1 being broken.

The other hooks you will use#

useRef holds a value that persists across renders without causing a re-render when it changes. Two uses: a handle to a DOM element, and a mutable box for things like timer ids.

JSX
const inputRef = useRef(null);
useEffect(() => { inputRef.current.focus(); }, []);
return <input ref={inputRef} />;

useContext reads a value provided somewhere above in the tree, so it does not have to be passed through every level as a prop. Theme, current user, language.

JSX
const ThemeContext = createContext('light');
// somewhere above: <ThemeContext.Provider value="dark">...</ThemeContext.Provider>
const theme = useContext(ThemeContext);

useMemo and useCallback cache a computed value or a function between renders so that expensive work is not redone and child components do not re-render needlessly. Reach for them when you have measured a problem, not by default; premature memoisation adds complexity and often no speed.

useReducer is useState for state with several related fields and transitions; if your setters are getting complicated, it is the next step.

Custom hooks#

Any function that calls hooks and starts with use is a custom hook. It is how you share stateful logic between components:

JSX
function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    try { return JSON.parse(localStorage.getItem(key)) ?? initial; } catch { return initial; }
  });
  useEffect(() => { localStorage.setItem(key, JSON.stringify(value)); }, [key, value]);
  return [value, setValue];
}

const [name, setName] = useLocalStorage('name', '');

The component using it does not know or care that storage is involved. Most real applications end up with a handful of these.

Questions people ask#

Do I still need class components?

No. Hooks cover everything classes did, and new React code is written with function components. You will meet classes in older codebases.

Why does my effect run twice in development?

React’s Strict Mode mounts components twice in development to surface effects that lack cleanup. It does not happen in production. If the double run causes a problem, the effect is missing its cleanup.

Should I fetch data in useEffect?

For learning, yes. In real applications, frameworks and libraries such as Next.js server components and TanStack Query handle fetching with caching and error handling; effects are the manual version.

What is the difference between useMemo and useCallback?

useMemo caches a value; useCallback caches a function. The second is the first applied to functions.

Where to go next#

Next.js vs React: what the framework addsRead next

Keep reading

JavaScript

Asynchronous JavaScript

The event loop, callbacks, promises and async/await — what actually happens when JavaScript waits, and the four mistakes that cause most async…

6 min read

Keep going — pick your next guide

The fastest way to improve is to read one guide, then build the thing it describes. Start with the basics, or jump straight to a project.

Ask a question or share what worked

Your email address will not be published. Required fields are marked *