#reactjs#typescript#beginers
First of all, we will clarify the concept of `memo`:
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 Button from "./components/Button";
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 />
<span>Counter: {counter}</span>
<Button
className="bg-black text-white"
onClick={handleIncrease}
>
Increment
</Button>
</div>
);
}
export default App;
With this code, do you understand? It's simply a small example of counting increments each time the `Increment` button is clicked. Each time you click on the `Increment` button, it will call the `handleIncrease` function and setCounter will be called, resulting in the parent component being re-rendered and the `counter` variable being updated, meaning that after each button click, it will automatically increase by 1 unit, and the child component `<TitleComp />` will also be called again.
I will prove to you that what I say is completely correct. Update child component:
function TitleComp() {
/* add console */
console.log("re-rendering....");
return <h1>HelperDev</h1>;
}
export default TitleComp;
After updated code, make a click on the button and open your browser and look at the console.log. I believe you have noticed the second problem that I mentioned at the beginning of the article!!
Next, so how to fix this? Don't worry, I will help you handle it.
In this case the child component does not necessarily need to be called again. Why? Because the child component does not use the state or anything related to the parent component, it does not necessarily have to be called again when the parent component re-render.
In the child component, update the code below. And `memo` will show you its features:
import { memo } from "react";
function TitleComp() {
/* add console */
console.log("re-rendering....");
return <h1>HelperDev</h1>;
}
export default memo(TitleComp); /* HOC - memo */
Now, you can test it yourself again. I guarantee you will love this.
Wowwww🤩🤩🤩🤩
Finally, don't forget to leave your opinion below in the comments section!!! 🤩🤩🤩🤩