Last active
August 30, 2022 05:56
-
-
Save luismartinezs/2a31469b59a0080a693c8113abf5788c to your computer and use it in GitHub Desktop.
React useStableCallback #react #hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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