New Hook for OptimizationšŖ
Optimize your app better.
If you are a React Developer, you probably use useCallback a lot, in your app to optimize it.
But in some cases, this hook will be useless!
Letās take an example:
If you have an input for email and a button to subscribe:
you probably will manage email value with setState hook;
And a function to subscribe called onSubscibe for instance
const [email, setEmail] = useState("")const onSubscibe = () => {
// call your Web Service API and subscibe this email. API.subscibe(email)
}return (...)
Seems good, now you want to enhance your app, so you use useCallback to stop the onSubscibe function re-assignment.
So your code will be like so:
const [email, setEmail] = useState("")const onSubscibe = useCallback(() => {
// call your Web Service API and subscibe this email.
API.subscibe(email)
}, [email])return (...)
and here we notice that our subscribe function will be re-assign every time the user makes an input event, and this will make no changes in our app performance; It Seems ridiculous uh!
Custom Hook To Solve this:
Okay, now we must try to prevent our subscribe function to re-assign again.
In this case, we must make our custom hook:
Letās think, we have the useRef hook that persists his value from changing during the re-rendering and doesnāt make react re-render if he changed, and we make a life cycle hook to make this ref up to date with the email state, and what I think is to go with useLayoutEffect because it runes before any layout effect (browser painting), so itās the one.
and our custom hook will be like this:
const useSafeCallback = (callback) => {
const callbackRef = useRef(); const memoCallback = useCallback((args) => {
if (typeof callbackRef.current === "function") {
return callbackRef.current(args);
} else {
return;
}
}, []); useLayoutEffect(() => {
callbackRef.current = callback;
return () => {
callbackRef.current = undefined;
};
}); return memoCallback;};
So the memoCallback function will be defined once, but the useLayoutEffect will be responsible for assigning the ended callback to the callbackRef and cleaning it when unmount.
Finally, you can get a look at the final code here:
Finally
This new hook is Under Construction right now, you can know more just take a look at Dan Abramovās RFC here: https://beta.reactjs.org/apis/react/useEvent
Thanks!