useSetState
useState wrapper to work with state like in class component
useSetState returns a [state, setState] tuple where setState accepts a partial object (or a function returning a partial object) and merges it into the current state, just like this.setState in React class components. This avoids the need to spread the previous state manually when updating a single field in an object.
When to Use
- Managing complex form state with many fields where you want to update one field at a time without spreading the rest
- Migrating class components to hooks while preserving the familiar
this.setState({ key: value })pattern - Any scenario involving an object state where partial updates are more ergonomic than full replacements
Notes
- Shallow merge: The partial object is merged one level deep via object spread. Nested objects are replaced, not deeply merged.
- Function updater: You can pass a function
(currentState) => Partial<T>for updates that depend on the current state. - SSR-safe: Uses only React state internally with no browser dependencies.
Usage
Live Editor
function Demo() { const [state, setState] = useSetState({ value1: "value1", value2: "value2" }); const { value1, value2 } = state; return ( <div> <p>value1: {value1}</p> <p>value2: {value2}</p> <button onClick={() => { setState({ value1: "value", }); }} > change value </button> </div> ); };
Result
API
useSetState
Returns
readonly [T, (statePartial: Partial<T> | ((currentState: T) => Partial<T>)) => void]: A tuple with the following elements:
- The current value of the state.
- A function to update the value of the state.
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| initialState | initial value | T (Required) | - |