Sub topic 1
Why a Local Variable Is Not Enough
Prerequisites
This chapter assumes JavaScript functions, destructuring, arrow functions, basic JSX, and function components. You should also know how to pass props to a component.
Why a Local Variable Is Not Enough
A function component runs again whenever React renders it. A local variable is created again on every run, so it cannot remember a value between renders. Changing that variable also does not tell React to render the component again.
React state is component data that React remembers between renders. Updating state schedules another render.
Declaring State with `useState`
useState is a React Hook that adds state to a function component. It returns an array with the current value and a setter function.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}The argument 0 is the initial state. The count variable is the value for the current render. The setCount function requests a new value.
How a State Update Triggers a Re-render
When handleClick calls setCount, React stores the requested state and renders Counter again. During the next render, count contains the new value. React then updates the button text in the browser.
Updating State from Event Handlers
Event handlers are functions that respond to actions such as clicks or typing. Pass the handler to JSX instead of calling it while rendering.
A setter does not immediately change the count variable already used by that render. It requests a future render.
State Is a Snapshot for Each Render
Each render receives a fixed snapshot of state. Every handler created during that render sees that snapshot. If count is 0, calling setCount(count + 1) three times still requests 1 three times. Use an updater function when a new value depends on the previous value:
setCount(current => current + 1);The updater receives the latest pending value, so repeated updates can build on one another.
Exercise
Why does changing a local variable fail to update a component's displayed value?
Show answer
React does not remember the variable across renders or know that it should render again. State provides memory and its setter schedules a re-render.