Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/apuchenkin/react-state-effects
React useState hook enhanced with side effects
https://github.com/apuchenkin/react-state-effects
hooks react reactjs
Last synced: 23 days ago
JSON representation
React useState hook enhanced with side effects
- Host: GitHub
- URL: https://github.com/apuchenkin/react-state-effects
- Owner: apuchenkin
- Created: 2019-06-08T12:26:15.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-03T23:41:12.000Z (about 2 years ago)
- Last Synced: 2024-11-26T01:12:57.829Z (about 2 months ago)
- Topics: hooks, react, reactjs
- Language: TypeScript
- Size: 551 KB
- Stars: 0
- Watchers: 0
- Forks: 1
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# React `useStateEffects` hook
Allows excecution of side effects immediately after state is set by `setState` hook.
## Example
```jsx
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:
```js
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:
```jsx
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;
}
```