developerasun / myCodeBox-web

Open source code box for web developers.
Apache License 2.0
5 stars 0 forks source link

React/Hooks : useCallback #197

Open developerasun opened 2 years ago

developerasun commented 2 years ago

research : understanding useCallback hook in React

read this

That's just how JavaScript objects works. An object (including a function object) equals only to itself.

the hook returns the same function instance between renderings (aka memoization):

By using useCallback() you also increased code complexity. You have to keep the deps of useCallback(..., deps) in sync with what you're using inside the memoized callback.

reference

developerasun commented 2 years ago

read this

Every time a component re-renders, its functions get recreated

The React useCallback Hook returns a memoized callback function. Think of memoization as caching a value so that it does not need to be recalculated. This allows us to isolate resource intensive functions so that they will not automatically run on every render.

The useCallback Hook only runs when one of its dependencies update. This can improve performance. The useCallback and useMemo Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function. You can learn more about useMemo in the useMemo chapter.

reference

developerasun commented 2 years ago

usage example

we can use the useCallback hook to prevent the function from being recreated unless necessary. Use the useCallback Hook to prevent the Todos component from re-rendering needlessly:

// index.js
import { useState, useCallback } from "react";
import ReactDOM from "react-dom";
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>
    </>
  );
};

ReactDOM.render(<App />, document.getElementById('root'));

// todo.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);

reference