react-state-effects
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

React useStateEffects hook

Allows excecution of side effects immediately after state is set by setState hook.

Example

import useStateEffects from 'react-state-effects';

const Example = ({ callback, children }) => {
  const [state, setState] = useStateEffects(1);

  React.useEffect(() => {
    setState(state$ => [state$ + 1, callback]);
  }, [])

  return children;
}

setState could accept zero, one or multiple callbacks:

const cb1 = () => {...}
const cb2 = () => {...}

setState(state => [state + 1]);
setState(state => [state + 1, cb1]);
setState(state => [state + 1, cb1, cb2]);

In case current state is needed within callback, latest state could be injected by saving it within ref:

import useStateEffects from 'react-state-effects';

const Example = ({ callback, children }) => {
  const [state, setState] = useStateEffects(1);
  const stateRef = React.useRef(state);

  React.useEffect(() => {
    setState(state$ => [state$ + 1, () => callback(stateRef.current)]);
  }, [])

  React.useEffect(() => {
    stateRef.current = state;
  }, [state])

  return children;
}

Readme

Keywords

none

Package Sidebar

Install

npm i react-state-effects

Weekly Downloads

235

Version

1.0.4

License

MIT

Unpacked Size

13.5 kB

Total Files

10

Last publish

Collaborators

  • apuchenkin