mirror of
https://github.com/streamich/react-use.git
synced 2025-12-08 18:02:14 +00:00
45 lines
891 B
Markdown
45 lines
891 B
Markdown
# `useSetState`
|
|
|
|
React state hook that creates `setState` method which works similar to how
|
|
`this.setState` works in class components—it merges object changes into
|
|
current state.
|
|
|
|
|
|
## Usage
|
|
|
|
```jsx
|
|
import {useSetState} from 'react-use';
|
|
|
|
const Demo = () => {
|
|
const [state, setState] = useSetState({});
|
|
|
|
return (
|
|
<div>
|
|
<pre>{JSON.stringify(state, null, 2)}</pre>
|
|
<button onClick={() => setState({hello: 'world'})}>hello</button>
|
|
<button onClick={() => setState({foo: 'bar'})}>foo</button>
|
|
<button
|
|
onClick={() => {
|
|
setState((prevState) => ({
|
|
count: (prevState.count || 0) + 1,
|
|
}))
|
|
}}
|
|
>
|
|
count
|
|
</button>
|
|
</div>
|
|
);
|
|
};
|
|
```
|
|
|
|
## Reference
|
|
|
|
```js
|
|
const [state, setState] = useSetState({cnt: 0});
|
|
|
|
setState({cnt: state.cnt + 1});
|
|
setState((prevState) => ({
|
|
cnt: prevState + 1,
|
|
}));
|
|
```
|