Skip to content

Instantly share code, notes, and snippets.

@lovetingyuan
Created August 23, 2023 07:55
Show Gist options
  • Save lovetingyuan/293bcb5794bbe7fa86ac97d756a2ee45 to your computer and use it in GitHub Desktop.
Save lovetingyuan/293bcb5794bbe7fa86ac97d756a2ee45 to your computer and use it in GitHub Desktop.
// 当你在react hook中想读取或者设置某个值但是并不关心它们的变化时,可以使用下面的hook
export function useGetState(data) {
const [val, setVal] = React.useState(data);
const currentValRef = React.useRef(val);
currentValRef.current = val;
return React.useCallback((...args) => {
if (args.length) {
setVal(args[0]);
} else {
return currentValRef.current;
}
}, []);
}
@lovetingyuan
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment