Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

React Hooks are functions that let a function component use React features such as state, context, refs, effects, and performance caching. You choose a Hook by the job it does. useState stores a value that changes over time, useEffect keeps a component synchronized with something outside React, useContext reads a value shared by a provider higher in the tree, and useMemo or useCallback are targeted tools for caching, not defaults you should add everywhere.

What Hooks do and how to pick one

Hooks are the way modern React components hold state, read shared data, and connect to the outside world. The official built-in Hooks reference on react.dev groups them into state, context, refs, effects, performance, and other APIs. Start with the problem in front of you, then pick the Hook that matches it.

The problem Hook to start with Typical use
A value changes and the screen should update useState Form input, a toggle, a counter
State updates follow several related rules useReducer A form with many fields and actions that change them together
Read a value provided higher in the tree useContext Theme, current user, language preference
Keep a component in sync with an external system useEffect Subscribing to a connection, timers, a browser API, a non-React widget
Cache an expensive calculation result useMemo A costly derived value that must be recomputed only when its inputs change
Cache a function definition useCallback A function passed to a memoized child component or used as an Effect dependency

The Rules of Hooks

The official Rules of Hooks page sets the constraints for ordinary Hooks. Break them and React cannot reliably match each Hook call to its stored state between renders.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Call Hooks only at the top level of a function component or a custom Hook.
  • Call them before any early return in the component body.
  • Call them only from React function components or custom Hooks, not from ordinary JavaScript helper functions.
  • Never call them inside conditions, loops, nested functions, or event handlers.
  • Never call them inside class components.

The rule is about call order, not about values. If you need different behaviour, put the condition inside the Hook’s logic or split the component into two components.

The exception: the use API

The React use API follows different rules, and it is easy to overgeneralize from the ordinary Hook rule. The official lint documentation states that use may be called conditionally and in loops. The API reference page, however, still says it must be called inside a component or a Hook. Read both pages before relying on use in a conditional branch.

Storing component state with useState

useState declares a state variable. It returns the current value and a setter function. Calling the setter asks React to update the state and re-render the component.

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <button onClick={() => setCount(count + 1)}>
      Clicked {count} times
    </button>
  );
}

The argument you pass to useState is used only on the first render. On later renders React keeps the value it already stored, so passing a new initial value does not reset the state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Initial state and initializer functions

If the starting value is expensive to compute, pass a function instead of a value. React calls that function once to get the initial state. Pass the function itself, not its result: useState(createInitialTodos), not useState(createInitialTodos()). The initializer must be pure, meaning it should return the same result for the same inputs and must not change anything else in the app.

In development with Strict Mode enabled, React may call the initializer twice. This is intentional. If your initializer has side effects, the doubled call exposes them.

useReducer for related update logic

Use useReducer when the logic for changing state is complicated enough that it belongs in one place. The difference from useState is where the update logic lives. With useState, each event handler decides the next value. With useReducer, event handlers dispatch actions and a reducer function computes the next state. For a single toggle or counter, useState is simpler.

Synchronizing with useEffect

The official useEffect page defines an Effect as a way to synchronize a component with an external system. Examples include a network connection, a browser API, an animation library, or a non-React widget. You pass a setup function and, optionally, a dependency array. React runs setup after the component appears on screen and runs it again when a dependency changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { useEffect, useState } from "react";

function ChatStatus({ roomId }) {
  const [online, setOnline] = useState(false);

  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();
    connection.onStatus(setOnline);
    return () => {
      connection.disconnect();
    };
  }, [roomId]);

  return <p>{online ? "Online" : "Offline"}</p>;
}

The function returned from setup is the cleanup. React calls it before the Effect runs again and when the component unmounts. Cleanup should undo whatever setup did, such as closing a connection, clearing a timer, or removing an event listener. The dependency array tells React when the synchronization must repeat. Missing dependencies are a common source of stale values, so list every reactive value the Effect reads.

When you do not need an Effect

The official page cautions that an Effect may be unnecessary if your goal is not to synchronize with an external system. Two common cases are calculating a value from props or state during render, and responding to a user event. Put derived values directly in render, and put user-triggered work in the event handler. An Effect that only copies one state value into another usually adds an extra render for no benefit.

Strict Mode in development

When Strict Mode is enabled, React runs one extra development-only setup and cleanup cycle before the first real setup. This exposes Effects whose cleanup does not fully undo their setup. In production this extra cycle does not run, so the bug can appear only after deployment if you skip it in development. Treat any failure in the double run as a real defect.

Reading shared values with useContext

useContext reads a context value and subscribes the component to changes. The value comes from the nearest matching provider above the component. If no provider exists, the component receives the default value that was given when the context was created.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Context lets you pass information through many layers without adding it to every intermediate component’s props. Use it for values many components need, such as a theme or the signed-in user. For data that only a parent and one child need, ordinary props are usually clearer.

Caching with useMemo and useCallback

Both Hooks keep a value between renders as long as their dependencies are unchanged. They differ in what they cache.

useMemo useCallback
What it caches The result of a calculation A function definition
Call shape useMemo(() => compute(a, b), [a, b]) useCallback(fn, [a, b])
Returns The cached result The cached function
Equivalent form Not applicable Same as useMemo(() => fn, [a, b])

Use useMemo when a calculation is genuinely expensive and its result is passed to something that depends on identity or is repeatedly recomputed. Use useCallback when a function is passed to a child component wrapped in memo, or when a function is an Effect dependency. The official reference frames both as targeted performance tools. It does not present them as universal improvements, and it does not establish performance gains for typical components.

React Compiler and manual memoization

The official useCallback reference notes that React Compiler automatically memoizes values and functions, which reduces the need to write these calls by hand. Whether the compiler is active depends on your project’s build setup, so check that before removing existing memoization or adding new calls. Code that already uses these Hooks keeps working either way.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Keep render pure

Rendering a component should only calculate what the screen should show. It should not write to variables outside the component, change props or state that already exist, send network requests, or start timers. Those actions belong in event handlers or Effects. The official Rules of React page puts it this way:

“Purity in Components and Hooks is a key rule of React that makes your app predictable, easy to debug, and allows React to automatically optimize your code.”

The quote is from the React documentation on react.dev. The page does not attribute it to an individual author.

Learning resources

The React documentation at react.dev is the primary reference and is free. If you prefer an offline reference, a printed or e-book React Hooks programming book can serve as a supplement. Choose one published recently, because Hook guidance changes with React releases. This is optional. You do not need a book to use Hooks correctly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a broader overview of the surrounding JavaScript and React concepts, see the other tutorials on itechguides.com.

“

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.