October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

React Hooks: A Practical Guide to State, Effects, and Reusable Logic

A practical React Hooks guide: choose the right Hook for state, context, refs, and Effects, follow call-order rules, and package reusable logic with custom Hooks.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

React Hooks let function components use features such as state, context, refs, and Effects. Start with the problem a component needs to solve: use state for information that affects the screen, context for values provided by an ancestor, refs for values that should not trigger rendering, and Effects to synchronize with external systems. Call Hooks at the top level of a component or custom Hook, and use React’s lint rules to catch common mistakes.

What are React Hooks?

Hooks are functions that let function components use React features. Built-in Hooks cover needs such as remembering state, reading context, holding a reference, synchronizing with an external system, and optimizing work. You can also combine Hooks to package reusable behavior.

As an Amazon Associate I earn from qualifying purchases.

Rather than memorizing a flat list, choose a Hook based on the problem: does the component need to remember something that changes, read a value supplied higher in the tree, keep a non-rendering value, or coordinate with something outside React?

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

How do I keep changing information in a component?

Use useState for values that affect rendering

useState gives a component a state value and a setter function. Call it at the top level of the component:

import { useState } from 'react';

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

  function handleClick() {
    setCount(count + 1);
  }

  return <button onClick={handleClick}>Count: {count}</button>;
}

Calling the setter requests an update, and React renders the component again with the updated state. The count variable in a particular render is a snapshot: calling setCount does not change that variable immediately inside the already-running event handler. See React’s useState reference.

Use context when an ancestor provides the value

Context lets a component read information made available by an ancestor, without passing that value through every intermediate component as props. It addresses a different need from local state: the value is provided through the component tree rather than owned solely by the component reading it. React lists context among its built-in Hooks.

Use refs for values that should not trigger a render

A ref can hold a DOM node or a value such as a timeout ID. Updating a ref does not cause a re-render, so it is appropriate for information that the component needs to retain but does not use to determine the rendered output. If a value must update what appears on screen, state is generally the relevant tool.

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

When should I use useEffect?

Use useEffect to synchronize a component with an external system, such as a chat connection, browser API, or third-party widget. It is not a general-purpose place for calculations or ordinary data flow that can happen during rendering or in response to an event. If there is no external system to synchronize with, an Effect may not be needed.

Pair setup with cleanup

For example, a chat connection should be opened for the selected room and disconnected when that synchronization is no longer needed:

import { useEffect } from 'react';

function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();

    return () => {
      connection.disconnect();
    };
  }, [roomId]);

  return <h1>Chat room: {roomId}</h1>;
}

The setup reads roomId, so the dependency list includes it. Dependencies describe the reactive values used by the synchronization; they are not a general scheduling control. When a dependency changes or the component is removed, cleanup disconnects the connection associated with the previous setup. The useEffect reference explains this setup-and-cleanup model.

Understand Strict Mode’s extra development cycle

In development, React Strict Mode runs an additional setup-and-cleanup cycle for Effects to help expose cleanup problems. This is intentional. Make cleanup correctly undo the setup rather than suppressing the extra cycle as a first fix.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

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

Be deliberate about data fetching

Fetching directly in Effects can lead to repetitive code and make caching and server rendering harder. React’s Effect guidance points toward extracting fetching behavior into custom Hooks or using a community data-fetching solution where appropriate; no single third-party option is required for every application.

Why can’t I call a Hook conditionally?

Call ordinary Hooks at the top level of a function component or custom Hook, before any early return. Do not call them in conditions, loops, nested callbacks, event handlers, or regular JavaScript functions. React relies on a consistent Hook call order between renders; changing that order can cause state to be associated with the wrong Hook.

The special React use API has different conditional-call rules from ordinary Hooks. Do not generalize those exceptions to Hooks such as useState or useEffect. React documents the restrictions and exceptions in its Rules of Hooks.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I write a custom Hook?

A custom Hook is a function that packages reusable behavior using one or more built-in Hooks. Its name conventionally starts with use followed by a capital letter, such as useOnlineStatus. Components can call it to share the behavior without duplicating its implementation.

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

Custom Hooks do not make conditional Hook calls safe: calls to built-in Hooks inside the custom Hook must still follow the Rules of Hooks. They reuse logic, not component state itself; each component calling a custom Hook runs that Hook’s logic in its own context. React’s guide to reusing logic with custom Hooks walks through the pattern.

How can I catch Hook mistakes while coding?

Enable React’s Hooks lint rules in your development environment. The Rules of Hooks lint rule can flag common call-order violations as you write code. React’s editor guidance recommends enabling all React Hooks rules and discusses VS Code, WebStorm, Sublime Text, and Vim. Choose the editor that suits your workflow, then confirm it supports your JavaScript lint setup and that the React Hooks rules are enabled.

  • Check that every ordinary Hook is called at the top level of a component or custom Hook.
  • Check that Hooks appear before early returns and are not nested inside conditions, loops, callbacks, or event handlers.
  • For each Effect, identify the external system it synchronizes with and ensure cleanup reverses setup where needed.
  • Include the reactive values used by Effect setup in its dependency list.

React’s Rules of Hooks lint documentation covers the lint rules, and its editor setup guide explains editor integration.

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.

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

Leave a Reply

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

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

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.