Home
React
useState() for State Management
July 27, 2025
1 min

Table Of Contents

01
What?
02
Functional Updates
03
Lazy Initialization
04
Best Practices

useState is the most fundamental React Hook. It allows function components to store and update state, making UIs dynamic and interactive.

What?

useState lets a component remember values between renders.

const [state, setState] = useState(initialValue)

It returns:

  • The current state value
  • A function to update it

Example

function Counter() {
const [count, setCount] = useState(0)
return (
<button onClick={() => setCount(count + 1)}>
{count}
</button>
)
}

Clicking the button updates the state and re-renders the UI.

Functional Updates

When new state depends on previous state:

setCount(prev => prev + 1)

This avoids bugs when updates happen quickly or in batches.

Objects and Arrays

Always copy state instead of mutating it:

const [user, setUser] = useState({ name: "Daniel" })
setUser(prev => ({ ...prev, name: "Alex" }))
setItems(prev => [...prev, newItem])

Lazy Initialization

For expensive initial state:

const [value, setValue] = useState(() => computeInitial())

This runs only once, not on every render.

Best Practices

✔ Keep state minimal
✔ Prefer functional updates
✔ Split unrelated state
✔ Lift state when needed
✔ Avoid deeply nested state


Tags

#ReactTesting

Share

Related Posts

React Fundamentals
useDeferredValue() for Responsive Inputs
July 30, 2025
1 min
© 2026, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube