How to Set Initial State in React: Simple Guide
In React, you set the initial state in a functional component by using the
useState hook and passing the initial value as an argument. This value becomes the starting state when the component first renders.Syntax
The useState hook is used to declare state in a React functional component. It returns an array with two items: the current state value and a function to update it.
const [state, setState] = useState(initialValue);stateholds the current value.setStateupdates the state and triggers a re-render.initialValueis the starting state when the component loads.
javascript
import React, { useState } from 'react'; function Example() { const [count, setCount] = useState(0); // initial state is 0 return null; }
Example
This example shows a button that starts with a count of 0. Each click increases the count by 1, demonstrating how the initial state is set and updated.
javascript
import React, { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); // initial state is 0 return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
Output
You clicked 0 times (initially)
Button labeled 'Click me' increments count on each click
Common Pitfalls
Some common mistakes when setting initial state in React include:
- Passing a function call instead of a function to
useStatewhen the initial state is expensive to compute. - Trying to update state directly instead of using the setter function.
- Setting initial state inside the component body without
useState, which won't persist across renders.
javascript
import React, { useState } from 'react'; // Wrong: calling function immediately function Wrong() { const [value, setValue] = useState(expensiveComputation()); // runs every render return null; } // Right: lazy initialization with function function Right() { const [value, setValue] = useState(() => expensiveComputation()); // runs once return null; } function expensiveComputation() { console.log('Computing...'); return 42; }
Output
Computing... (only once for Right component)
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Declare state | Use useState hook with initial value | const [count, setCount] = useState(0); |
| Update state | Call setter function with new value | setCount(count + 1); |
| Lazy init | Pass function to useState for expensive init | useState(() => compute()) |
| Do not mutate | Never change state variable directly | Wrong: count = 5; Right: setCount(5); |
Key Takeaways
Use the useState hook to set initial state in React functional components.
Pass the initial value directly or a function for lazy initialization to useState.
Always update state using the setter function returned by useState.
Avoid expensive computations on every render by using lazy initialization.
Never mutate state variables directly; always use the setter function.