#reactjs#javascript#typescript#beginers
First of all, we will clarify the concept of `useCallback`:
Now, I will create a problem so you can understand why it is necessary to fix it?
In file `App.tsx`:
import { useState } from "react";
import TitleComp from "./components/TitleComp";
function App() {
const [counter, setCounter] = useState<number>(0);
const handleIncrease = () => setCounter((prev) => prev + 1);
return (
<div className="flex items-center justify-center flex-col gap-4 h-[100vh]">
<TitleComp onIncrease={handleIncrease} />
<span>Counter: {counter}</span>
</div>
);
}
export default App;
Now, I will pass this `handleIncrease` function to the child component with props of `onIncrease` and the child component will look like this:
import { memo } from "react";
import Button from "./Button";
type TitleCompProps = {
onIncrease: () => void;
};
function TitleComp({ onIncrease }: TitleCompProps) {
/* add console */
console.log("re-rendering....");
return (
<>
<h1>HelperDev</h1>
<Button
className="bg-black text-white"
onClick={onIncrease}
>
Increment
</Button>
</>
);
}
export default memo(TitleComp); /* HOC - memo */
Okayyy. Now, you can press the `Increase` button and open your browser to see the console.log !
Oh no? What's going on with HOC memo? Why doesn't it work? 😢😢😢😢😢😢
I will explain it to you as follows:
In the parent component, update the code below. And `useCallback` and `memo` will show you its features:
import { useCallback, useState } from "react";
import TitleComp from "./components/TitleComp";
function App() {
const [counter, setCounter] = useState<number>(0);
/* hook - useCallback */
const handleIncrease = useCallback(() =>
setCounter(prev => prev + 1)
, []);
return (
<div className="flex items-center justify-center flex-col gap-4 h-[100vh]">
<TitleComp onIncrease={handleIncrease} />
<span>Counter: {counter}</span>
</div>
);
}
export default App;
Now, you can test it yourself again. I guarantee you will love this.
Wowwww🤩🤩🤩🤩
In short, a component can receive many props and those props can be primitive data types, or can be reference data types. If you determine to use HOC memo to avoid unnecessary re-rendering of child components, then all functions should use the `useCallback` hook to avoid unnecessary re-rendering !!
Finally, don't forget to leave your opinion below in the comments section!!! 🤩🤩🤩🤩