If you didn't catch my previous React built-in hooks blog about useActionState, this is a continuation of that series.
Previously I was introduced to useCallback when I asked ChatGPT once to optimize my frontend code, but I never took a deeper look into it (and frankly I regret it now), so I used it everywhere I could along with useMemo (which I'll cover later in this series).
While it's not inherently a signficant bad thing to have useCallback all around your code, it can clutter up the readability of your code, but it's encouraged you use it where needed.
So when should you use it? useCallback is meant for expensive callback functions that are used in granular applications like drawing software, as it loads the initial function on render but does not re-render like React usually does with its functions unless the dependencies change.
app/components/menu.jsx
"use client";
import { useState, useCallback } from "react";
import axios from "axios";
export default function Menu({ setMenu, menu }) {
const [newItem, setNewItem] = useState("");
const handleClick = useCallback(async () => {
try {
if(newItem){
const response = await axios.get("http://localhost:8000/menu");
setMenu([{name: newItem}, ...response.data]);
}else{
const response = await axios.get("http://localhost:8000/menu");
setMenu(response.data);
}
} catch (err) {
console.error(err);
}
}, [newItem]);
function addItem() {
setMenu([...menu, { name: newItem }]);
}
return (
<main>
<button onClick={() => handleClick()}>Click</button>
<input type="text" onChange={(e) => setNewItem(e.target.value)} />
<button
onClick={(e) => {
e.preventDefault();
addItem();
}}
>
Add Item
</button>
{menu && menu.length ? (
menu.map((item) => {
return (
<div key={item._id}>
<section>{item.name}</section>
</div>
);
})
) : (
<>Something went wrong, please try again later</>
)}
</main>
);
}
app/page.tsx
"use client"
import {useEffect, useState} from "react";
import axios from 'axios';
import Menu from "./components/menu.tsx";
export default function Home () {
const [menu, setMenu] = useState([]);
const [data, setData] = useState([]);
useEffect(()=>{
async function getMenu (){
const response = await axios.get("http://localhost:8000/menu");
setData(response.data);
}
getMenu();
},[]);
return(
<main>
{data.map((ele)=><>{ele.price}</>)}
<Menu setMenu = {setMenu} menu = {menu}/>
</main>
)
}
My hope with this series is to bring underrated built-in hooks to light, as well as highlight some things you may not have known about familiar hooks.
Top comments (0)