October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan 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

Hooked on React: A Beginner’s Guide to useState and useEffect

useState remembers component data between renders. useEffect synchronizes with external systems. Learn when each Hook belongs, and avoid common beginner mistakes.

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.

useState lets a React function component remember information between renders; useEffect lets it synchronize with something outside React. Think of state as a game screen remembering your hearts or selected item, and an Effect as connecting that screen to an external music player. The Zelda comparison is only a metaphor: each Hook has specific rules, and a state change does not automatically mean you need an Effect.

How do I use useState?

Call useState at the top level of a function component to give it a state variable and a setter:

As an Amazon Associate I earn from qualifying purchases.

import { useState } from 'react';

function HeartCounter() {
  const [hearts, setHearts] = useState(3);

  return (
    <button onClick={() => setHearts(value => value + 1)}>
      Hearts: {hearts}
    </button>
  );
}

Here, hearts is the value for the current render, initialized to 3, and setHearts requests a render with a new value. The setter does not mutate the variable in the already-running render. If you call it in an event handler and then immediately read hearts, that read still sees the value captured by that render. React supplies the requested state on a subsequent render. See the official useState reference.

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

When the next value depends on the previous one, pass an updater function, as in setHearts(value => value + 1). React applies it to the pending state. This form avoids calculating the next value from a potentially outdated variable when updates are queued.

State is for information that can change and needs to be remembered between renders, such as a score, a selected item, or text entered into a form. It is not a general-purpose container for every value used while rendering. If a value can be calculated from the current props or state, calculate it during render instead.

Where should Hooks go?

Call Hooks such as useState and useEffect at the top level of a function component or custom Hook, before any conditional return. Do not call them inside a condition, loop, event handler, or nested function. Keeping calls in the same order on each render lets React associate each Hook call with the right component data. The Rules of Hooks explain this requirement.

function GameScreen({ showMusic }) {
  const [hearts, setHearts] = useState(3);

  useEffect(() => {
    // Synchronization belongs here when it is needed.
  }, []);

  if (!showMusic) {
    return <p>Music is off</p>;
  }

  return <p>Hearts: {hearts}</p>;
}

The example shows placement only; an empty Effect is not useful in real code. Put a condition inside an Effect when necessary, rather than conditionally calling the Hook itself.

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

When do I need an Effect?

Use useEffect when a component needs to synchronize with an external system after React has rendered it. Examples include a network connection, a browser API, or a non-React widget. It is not a way to make React notice a state change: the setter already requests a render. React’s guide to synchronizing with Effects and useEffect reference describe this boundary.

For example, a component might connect to an external game-music service while it is on screen and disconnect when it is removed or the connection details change:

import { useEffect } from 'react';

function MusicConnection({ roomId }) {
  useEffect(() => {
    const connection = createMusicConnection(roomId);
    connection.connect();

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

  return null;
}

createMusicConnection stands for an external connection API; it is not a built-in React function. The Effect sets up the connection for the current roomId, and its returned cleanup disconnects it. If roomId changes, React cleans up the previous connection before setting up the new one.

How dependencies work

The dependency list describes the reactive values the Effect reads to establish its synchronization. React compares each dependency with its previous value using Object.is. When a dependency changes, React runs the prior cleanup, if one was returned, and then runs setup with the new values. Dependencies are not a timing dial: include the reactive values the Effect uses rather than omitting one to force a preferred schedule.

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

Effects are for synchronization with external systems, not for arranging ordinary data flow between React values. For instance, if a displayed value is simply a calculation from existing props and state, compute it during render rather than copying it into state with an Effect. The latter adds another update step and can leave the copied value out of sync.

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

How are useState and useEffect different?

Question useState useEffect
Main job Remember component information and request a render when it changes. Synchronize the component with an external system.
Typical reason it runs A setter is called, often in response to an interaction. A render commits and the synchronization must be established or updated.
Cleanup No setup/cleanup pair; the setter supplies a next state. Setup can return cleanup to undo a connection, subscription, or other ongoing synchronization.
Common beginner mistake Expecting the state variable in the current render to change immediately. Using an Effect for data that can be calculated during render.

What should I watch out for?

  • Do not expect an immediate state-variable change. A setter requests a future render; it does not rewrite values captured by the current handler.
  • Do not duplicate derived data in state. If a value follows directly from props and state, calculate it during render instead of synchronizing a second copy with an Effect.
  • Do not hide Effect dependencies to control timing. Identify the reactive values the Effect reads and make the synchronization reflect them.
  • Keep setup and cleanup paired. For a subscription or connection, cleanup should undo what setup established.
  • Do not mistake Strict Mode’s development check for production behavior. In development, React Strict Mode runs an extra setup/cleanup cycle before the first real setup to check that cleanup mirrors setup. This is not a production double-run.

For an overview of React’s built-in Hooks, see the official Hooks index.

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.

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.