State
What is State?
State serves as a component's memory, allowing it to store and track information between renders.
The useState
Hook
useState
HookThe useState
hook enables state management in functional components. It accepts an initial value and returns an array containing:
The current state value
A function to update that value
const [currentValue, setValue] = useState(initialVal);
// example:
const [color, setColor] = useState(defaultColor);
Note: useState(initialVal)
returns an array, ["val", "func"]
destructures the array to access the elements and assign it to a specific name.
React's Rendering Process
When a component's state or props change, React performs a rerender by:
Destroying the current component instance (including all variables and functions)
Recreating it with the updated state values
During this process, React maintains state consistency by providing the latest values to the recreated component. The initial value is only used on the first render.
Implementing State Variables
To add state:
Import useState:
import { useState } from "React";
Replace regular variables with state:
// Before
let counter = 0;
// After
const [counter, setCounter] = useState(0);
Update state using a setter function:
function increment() {
setCounter(counter + 1);
}
// or you can declare an arrow/anonymous function, which is more modern
const increment = () => setCounter(counter + 1);
Additional resources:
Last updated