Skip to content

Instantly share code, notes, and snippets.

@luismartinezs
Last active August 30, 2022 05:56
Show Gist options
  • Save luismartinezs/2a31469b59a0080a693c8113abf5788c to your computer and use it in GitHub Desktop.
Save luismartinezs/2a31469b59a0080a693c8113abf5788c to your computer and use it in GitHub Desktop.
React useStableCallback #react #hooks
// https://blog.thoughtspile.tech/2021/04/07/better-usecallback/
const useStableCallback = (callback) => {
const onChangeInner = useRef(callback);
// Added useLayoutEffect here, to work with concurrency
// Because of this, it can't be used during render, only after render
useLayoutEffect(() => {
onChangeInner.current = callback;
});
const stable = useCallback((...args) => onChangeInner.current(...args), []);
return stable;
};
function FormItem({ name, value, onChange, ...props }) {
const onChange = useStableCallback(e => {
onChange({ ...value, [name]: e.target.value });
});
return <HeavyInput onChange={onChange} value={value[name]} {...props} />;
};
function LoginForm() {
const [formValue, setFormValue] = useState({
username: '',
password: '',
});
return (<>
<FormItem name="password" value={formValue} onChange={setFormValue} />
<FormItem name="username" value={formValue} onChange={setFormValue} />
</>);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment