Documentation Index
Fetch the complete documentation index at: https://mintlify.com/Byrontosh/FundamentosReact/llms.txt
Use this file to discover all available pages before exploring further.
useState is React’s foundational state hook. It lets a function component remember a value between renders and, crucially, tells React to re-render the component whenever that value changes. Before hooks existed, only class components could hold local state; useState brings the same capability to any function component with a single line of code. Every piece of interactive UI you build in React — counters, form inputs, toggles, fetched data — will rely on useState at some level.
Hook signature
useState accepts an initial value and returns a two-element array: the current state value and a setter function. JavaScript destructuring lets you name both elements in a single declaration.
state— the current value for this render.setState— call this to schedule a state update; React will re-render the component with the new value.initialValue— used only on the first render; ignored on all subsequent renders.
Counter demo
TheSegundo component from the project implements a classic like-counter with three controls: increment, reset, and decrement. It uses a single useState call to manage the count.
How it works
- Initial value —
useState(0)setscounterto0the first timeSegundomounts. React stores this value internally and ignores the argument on every subsequent render. - Setter function —
setCounteris the only way to updatecounter. CallingsetCounter(counter + 1)schedules a re-render with the new value; React batches multiple calls within the same event handler before committing a single update. - Re-render on state change — each time
setCounteris called with a value that differs from the current one, React re-rendersSegundoand the JSX reflects the updatedcounter. - Functional updates pattern — when the next state depends on the previous state, pass an updater function instead of a value:
setCounter(prev => prev + 1). This guarantees you read the most recent state even if multiple updates are batched together, and is especially important inside async callbacks or event handlers that close over a stale value.
Calling the setter with the same value as the current state does not trigger a re-render. React uses
Object.is to compare the old and new values. For primitives like numbers and strings this works exactly as you would expect. For objects and arrays, Object.is checks reference equality — so mutating an object in place and passing the same reference will not schedule a re-render. Always create a new object or array when updating state that holds a non-primitive value.