use-get-set
v4.7.0arrow_drop_downv4.7.0
STATUS
Passing
DOWNLOADS
40
VISIBILITY
Public
PUBLISHED
6 years ago
SIZE
N/A
1 contributor
Like
Install use-get-set as a package?
Copied
npm i @bit/giladshoham.react-hooks.use.use-get-set
Set Bit as a scoped registryLearn more
npm config set '@bit:registry' https://node.bit.cloud
Component Example
React
React
Vue
Angular
React Native
Add dependency... help_outline
Just
and packages in Bit or NPM to the example. any of the 1 million componentstoggle layout
chevron_left
chevron_right
useGetSet
React state hook that returns state getter function instead of raw state itself, this prevents subtle bugs when state is used in nested functions.
Usage
Below example uses useGetSet
to increment a number after 1 second
on each click.
import {useGetSet} from 'react-use';
const Demo = () => {
const [get, set] = useGetSet(0);
const onClick = () => {
setTimeout(() => {
set(get() + 1)
}, 1_000);
};
return (
<button onClick={onClick}>Clicked: {get()}</button>
);
};
If you would do this example in a naive way using regular useState
hook, the counter would not increment correctly if you click fast multiple times.
const DemoWrong = () => {
const [cnt, set] = useState(0);
const onClick = () => {
setTimeout(() => {
set(cnt + 1)
}, 1_000);
};
return (
<button onClick={onClick}>Clicked: {cnt}</button>
);
};