dev-resources.site
for different kinds of informations.
The Magic of useCallback โจ
Hey there, devs! ๐
Today, I stumbled upon something that absolutely blew my mind: useCallback
. It's a game-changer in React, and I canโt wait to share how it saved me from a frustrating issue and made my code so much better. Let me walk you through my little adventure! ๐
The Problem ๐ง
I had this function for handling submenu clicks:
const handleSubmenuClick = (submenuName: string) => {
switch (submenuName) {
case "add_user":
router.push("/manage/users/add");
break;
case "update_user":
if (!user_id) {
alert("Please Select One Atleast!");
}
if (user_id) {
router.push(`/manage/users/edit/${user_id}`);
}
break;
default:
}
};
Seems fine, right? But here's the catch: every time the component re-rendered, this function would be re-created. That meant unnecessary re-renders and even some weird UI behavior, like the page feeling like it was refreshing. ๐ฉ Not what I wanted!
Enter useCallback
๐ช
I needed a way to prevent this function from being recreated unless its dependencies (like user_id
or router
) actually changed. That's where the useCallback
hook came to the rescue! ๐ฆธโโ๏ธ
Hereโs how I rewrote the function:
const handleSubmenuClick = useCallback(
(submenuName: string) => {
const routes: { [key: string]: string } = {
add_user: "/manage/users/add",
update_user: user_id ? `/manage/users/edit/${user_id}` : "",
};
if (submenuName === "update_user" && !user_id) {
alert("Please Select One Atleast!");
return;
}
const route = routes[submenuName];
if (route) {
router.push(route);
}
},
[router, user_id] // Dependencies
);
Why Is This So Cool? ๐
No more unnecessary re-creations!
WithuseCallback
, React remembers the function so it doesn't rebuild it unless therouter
oruser_id
changes. ๐พBetter performance.
No wasted re-renders or resource usage. ๐๏ธCleaner code.
By using an object (routes
) anduseCallback
, the logic became easier to follow and extend. ๐ ๏ธ
The Result ๐ฅณ
Now, my routing works smoothly, and thereโs no page "refresh" feeling. It's just like using the <Image>
component in Next.js: fast, snappy, and delightful. โก๏ธ
Here's a simplified version of the final function:
const handleSubmenuClick = useCallback(
(submenuName: string) => {
const routes = {
add_user: "/manage/users/add",
update_user: user_id ? `/manage/users/edit/${user_id}` : "",
};
if (submenuName === "update_user" && !user_id) {
alert("Please select a user first!");
return;
}
const route = routes[submenuName];
route && router.push(route);
},
[router, user_id]
);
Final Thoughts ๐ก
useCallback
is one of those hooks that feels like magic once you get it. It helps optimize performance, keeps your app running smoothly, and makes your code look much cleaner. ๐
If youโre not already using it, I highly recommend giving it a try. Itโs the kind of thing that makes you go, โWow, React is amazing!โ ๐
Happy coding! ๐ฅ๏ธโจ
Featured ones: