/use-reactive-state

useReactiveState() - a reactive alternative to React's useState()

Primary LanguageTypeScriptMIT LicenseMIT

useReactiveState() - a reactive alternative to React's useState()


Installation

$ npm install use-reactive-state

Example

useState() useReactiveState()
function Counter() {
  const [state, setState] = useState({count: 0});

  return (
    <div>
      <p>You clicked {state.count}</p>
      <button onClick={() => {
        setState({
          ...state,
          count: state.count + 1
        });
      }}>
        Click me
      </button>
    </div>
  );
}
function Counter() {
  const state = useReactiveState({count: 0});

  return (
    <div>
      <p>You clicked {state.count} times</p>
      <button onClick={() => { state.count += 1; }}>
        Click me
      </button>
    </div>
  );
}

Limitation of useReactiveState()

  • state cannot be destructured:
// This won't work
const {count} = useReactiveState({count: 0});
// This will work
const state = useReactiveState({count: 0});