To address this, use the useCallback Hook to prevent the function from being recreated unnecessarily, which will help avoid unnecessary re-renders of the Todos component.
Example:
index.js
import { useState , useCallback } from "react";
import ReactDOM from "react-dom/client";
import Todos from "./Todos";
const App = () => {
const [count , setCount ] = useState(0);
const [todos , setTodos ] = useState([]);
const increment = () => {
setCount((c) => c + 1);
};
const addTodo = useCallback(() => {
setTodos((t) => [...t , "New Todo"]);
}, [todos ]);
return (
<> <Todos todos={todos} addTodo={addTodo} /> <hr /> <div> Count: {count } <button onClick={increment}>+</button> </div> </>
); };
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<App />);
|
Todos.js
import { memo } from "react";
const Todos = ({ todos, addTodo }) => {
console .log("child render");
return (
<> <h2>My Todos</h2> {todos .map((todo, index) => {
return <p key={index}>{todo }</p>;
})} <button onClick={addTodo}>Add Todo</button> </>
); };
export default memo(Todos );
|
Now, the Todos component will re-render only when the todos prop changes.