react-use/docs/useSetState.md
Li Yan bfd114a407 feat: allow useSetState setter to accept function
* make setState of useSetState accept function argument

* update storybook
2018-11-02 08:50:04 +01:00

759 B

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

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 === undefined ? 0 : prevState.count + 1,
          }))
        }}
      >
        count
      </button>
    </div>
  );
};