Skip to content
Visual explainer 5h to learn 5 steps

State, events & conditional rendering

Add interactivity with useState and decide where each piece of state lives.

By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.

Topic 14 of 36

In short

State is data a component remembers between renders, created with useState. Calling the setter schedules a re-render with the new value, and React updates only what changed on screen.

Explained simply

Normal variables inside a component are forgotten every time it runs again. If you write let count = 0 and add one on click, the screen never changes. State is React's memory: a value that survives between renders and tells React to update the screen when it changes.

You create state with useState. It gives you the current value and a setter function. When you call the setter, React runs your component again with the new value and updates only the parts of the page that changed.

Events connect the user to state. onClick on a button or onChange on an input calls a function you write, and that function calls the setter. Conditional rendering then shows different UI depending on the state, such as a spinner while loading or a message when a list is empty.

A big part of React is deciding where state lives. If two components need the same value, put the state in their closest common parent and pass it down. And keep state small: if you can calculate something from existing values, do not store it twice.

Press Play on a diagram to walk through it one step at a time.

CycleHow a state update reaches the screen
  1. 1
    Event fires

    User clicks or types

  2. 2
    Call setter

    setCount(c => c + 1) queues an update

  3. 3
    Render

    React calls the component with the new state

  4. 4
    Commit

    React applies the differences to the DOM

  5. Back to step 1
SequenceWhat happens on one click
User
Event handler
React
Browser DOM
  1. 1click calls onClick
    User to Event handler: click calls onClick
  2. 2setCount(c => c + 1) queued
    Event handler to React: setCount(c => c + 1) queued
  3. 3handler finishes
    Event handler to React: handler finishes
  4. 4re-render with new state
    React to React: re-render with new state
  5. 5commit only the changed text
    React to Browser DOM: commit only the changed text

In depth

Snapshots and batching

Each render sees a fixed snapshot of state. Inside a click handler, count keeps its value from that render even after you call setCount. So calling setCount(count + 1) three times in a row adds only one: all three read the same old count.

React also batches updates. It waits until your event handler finishes, applies all queued updates together, and renders once. Since React 18 this happens everywhere, including inside timeouts and after await. If the next value depends on the previous one, pass an updater function: setCount((c) => c + 1). React queues the functions and runs them in order, each receiving the result of the one before.

CompareThree updates in one click, starting at 0
setCount(count + 1) x3
  • Each call reads the snapshot: 0
  • Queues: set to 1, 1, 1
  • One render with count 1
  • Result: 1
setCount(c => c + 1) x3
  • Each call queues a function
  • Runs 0 to 1, 1 to 2, 2 to 3
  • One render with count 3
  • Result: 3

Update objects and arrays by replacing them

React decides whether state changed by comparing the old and new value with Object.is. For objects and arrays, that compares references, not contents. If you push into the existing array and call setItems(items), the reference is the same, so React may skip the update and other code sees surprising changes.

Always create a new value. Add with [...items, newItem], remove with items.filter, change one item with items.map, and update an object field with { ...user, name }. For sorting, use toSorted, which returns a new array, instead of sort, which changes the original. For deeply nested data, consider flattening it, or use a helper like Immer.

  • Add: [...items, item]
  • Remove: items.filter((i) => i.id !== id)
  • Edit: items.map((i) => (i.id === id ? { ...i, done: true } : i))
  • Sort: items.toSorted(compareFn)

Choosing where state lives

Start by keeping state in the component that uses it. When a sibling also needs it, lift it up: move the state to the closest common parent, and pass the value and a setter function down as props. Now there is one source of truth, and both children always agree.

Lifting too high has a cost: every update re-renders the parent and everything under it. So lift only as far as needed. State that is used in one place, such as whether a dropdown is open, should stay local. Data from the server is a special case; in Next.js it often lives in server components and is not React state at all.

MapLifted state: one owner, two readers
FilterPage owns query
  • SearchInput
    • gets value={query}
    • calls onChange(text)
  • ResultList
    • gets query
    • filters during render
  • ResultCount
    • derives the count, no state

Avoid redundant state

Every extra piece of state is something that can get out of sync. If you store firstName, lastName and fullName, one day fullName will be stale. Calculate fullName during render instead. The same applies to filtered lists, totals and counts.

Other common fixes: do not copy a prop into state, because it will not update when the prop changes. Store an id, not a copy of the selected object, so edits to the list show up in the selection. Replace several booleans that can contradict each other, like isSending and isSent, with one status value such as "typing", "sending" or "sent".

Conditional rendering and the 0 trap

Use a ternary for either-or UI, && for show-or-hide, and an early return for whole-component cases like loading. Be careful with && and numbers: {items.length && <List />} renders the text 0 when the list is empty, because 0 is a value React can display. Write items.length > 0 instead.

State is tied to a component's position in the tree. If you render the same component in the same place, React keeps its state even if props change. To reset it on purpose, give it a different key: rendering a ChatPanel with key={contactId} gives each contact a fresh panel with an empty draft.

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Add state with useState~1h
  2. 2
    Handle click and input events~1h
  3. 3
    Render conditionally~1h
  4. 4
    Lift state up to a shared parent~1h
  5. 5
    Avoid redundant or duplicated state~1h

Key points

  • State is a snapshot; the new value appears on the next render, not immediately.
  • Use the updater form setX(prev => ...) when the new value depends on the old one.
  • Lift state to the closest common parent when siblings need the same data.
  • Derive values during render instead of storing duplicates in state.
  • Never mutate state objects; create new ones with spread.

Key terms

Tap a card to flip it. 0/5 known

Examples

tsx
import { useState } from 'react';

export function Counter() {
  const [count, setCount] = useState(0);
  const isEven = count % 2 === 0; // derived, not stored

  return (
    <div>
      <button onClick={() => setCount((c) => c + 1)}>+1</button>
      <p>{count} is {isEven ? 'even' : 'odd'}</p>
      {count > 5 && <p>That is a lot of clicks!</p>}
    </div>
  );
}

State, an updater function, a derived value and conditional rendering.

An accordion where only one panel is open

Each Panel used to keep its own isOpen, so several could be open at once. Step 1: remove the state from Panel. Step 2: the parent stores openId, a single value. Step 3: each Panel gets isOpen and onToggle props. Now opening one panel closes the other automatically, because there is only one source of truth.

tsx
import { useState, type ReactNode } from "react";

function Panel(props: { title: string; isOpen: boolean; onToggle: () => void; children: ReactNode }) {
  return (<section>
    <button aria-expanded={props.isOpen} onClick={props.onToggle}>{props.title}</button>
    {props.isOpen && <div>{props.children}</div>}
  </section>);
}
export function FAQ() {
  const [openId, setOpenId] = useState<string | null>(null);
  const toggle = (id: string) => setOpenId((cur) => (cur === id ? null : id));
  return (<>
    <Panel title="Shipping" isOpen={openId === "ship"} onToggle={() => toggle("ship")}>3 to 5 days</Panel>
    <Panel title="Returns" isOpen={openId === "ret"} onToggle={() => toggle("ret")}>30 days</Panel>
  </>);
}

Resetting a draft when the contact changes

A chat app shows one ChatPanel with a draft message. Bug: you type to Alice, switch to Bob, and the draft is still there. Step 1: understand why: same component, same position, so React keeps its state. Step 2: add key={contact.id}. Step 3: switching contacts now creates a fresh ChatPanel. No effect and no manual reset needed.

tsx
import { useState } from "react";

function ChatPanel({ name }: { name: string }) {
  const [draft, setDraft] = useState("");
  return <textarea aria-label={`Message ${name}`} value={draft} onChange={(e) => setDraft(e.target.value)} />;
}

export function Messenger({ contact }: { contact: { id: string; name: string } }) {
  return <ChatPanel key={contact.id} name={contact.name} />;
}

Quick reference

  • const [value, setValue] = useState(initial) gives a snapshot and a setter
  • New value depends on the old one? Use setX((prev) => next)
  • Never mutate state: copy with spread, map, filter or toSorted
  • Calculate derived values during render instead of storing them
  • {list.length > 0 && ...} avoids rendering a stray 0
  • Change a component's key to reset all of its state
  • useState(() => expensiveInit()) runs the initializer only on the first render
  • Lift state to the closest common parent of every component that needs it

Common mistakes

  • Reading state right after setting it and expecting the new value.
  • Mutating an array with push and calling setState with the same array.
  • Storing values in state that could be computed from props.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1count is 0. A click handler calls setCount(count + 1) twice. What is count after the re-render?

Question 2

2You call items.push(newItem) and then setItems(items). What is the problem?

Question 3

3count is 0. What does the expression count && (a paragraph element) render?

Question 4

4A form stores selectedProduct as a copy of an item from the products state. What is the better design?

Question 5

5How do you give a component fresh state when it starts showing a different user?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Build a LikeButton that shows a heart count, adds one per click, and changes its label to Liked after the first click.

  2. Exercise 2medium

    Build a shopping list: an input, an Add button, and a list where each item can be toggled done. Show "Nothing yet" when empty and a derived count of remaining items.

  3. Exercise 3hard

    A temperature converter has a Celsius input and a Fahrenheit input. Typing in either updates the other. Design the state so they can never disagree.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Why does my React state not update immediately?
The setter schedules a re-render; the current function keeps its snapshot. Use the new value you computed, or read the state in the next render.
When should I use useState vs a normal variable?
Use state for values that change over time and should update the screen. Use a normal variable for values you can calculate from props or state on every render.
Can I call a state setter during rendering?
Avoid it; it usually causes an infinite loop. Set state in event handlers or effects, or derive the value during render instead.

Go deeper

ShareXLinkedInWhatsApp