cd ../blog
6 min read React

React useState: Beyond a Simple Counter

State management can be tricky. Discover how to avoid unnecessary renders and how to handle complex states efficiently.

React Hooks State
React useState: Beyond a Simple Counter

## State Doesn't Update Instantly

A common mistake is thinking that right after calling `setState`, the value has already changed. In React, updates are asynchronous. If you need the previous value to calculate the new one, use a functional update:

javascript
setCount(prev => prev + 1);

## Handling Complex Objects

When your state is an object, you must be careful not to "overwrite" the rest of the properties. Always use the spread operator:

javascript
setUser(prev => ({ ...prev, name: 'Tomás' }));

## Curious Situations: Batching

React 18 introduced "Automatic Batching". If you call three `setState` functions in a row, React performs a single re-render for performance reasons. Understanding this helps you design much faster components and avoid data synchronization issues in the interface.

// Thanks for reading!