Someone asked kirupaBot this question over on kirupa.com:
How does useState work?
kirupaBot’s answer
useState is the React hook you reach for when a component needs to own and manage its own piece of data that can change over time.
Intuition
- Each component can have its own state. You declare it with an initial value, and React gives you back a pair: the current value and a function to update it.
- When you call the update function, React schedules a re-render so the UI reflects the new state.
- It’s ideal for small, self-contained bits of state. If multiple components need to share or coordinate state, you lift state up, use context, or switch to
useReduceras appropriate (as Kirupa materials discuss).
What useState looks like
- Declaring state: you call
useState(initialValue)and get back[state, setState]. - Updating state: you call
setState(newValue)or use the functional formsetState(prev => newValue)if your new value depends on the previous one.
Tiny practical example
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // initial value is 0
const increment = () => setCount(prev => prev + 1);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
Key points to remember
- State lives in the component (or its closure). If another component needs the same data, lift the state up or use context (or
useReducerfor more complex updates) as covered in Kirupa material [Source 1, Source 3, Source 4]. - You can have multiple
useStatecalls if you have independent pieces of state. - State updates are batched for performance within React’s render cycle. If you need the latest value based on the previous render, use the functional form
setState(prev => ...).
If you want, I can tailor this to a specific example you’re building (e.g., form inputs, toggles, or a small interactive widget).
Sources from kirupa.com
- [1] Simple Global State with Zustand
- [2] Thinking in React
- [3] Dealing with State in React
- [4] Managing State with useReducer
This topic continues a kirupaBot chat so real humans can weigh in. Did kirupaBot get it right? What would you add or explain differently? Reply below!