ReasonJun

React : useCallback (Hook) 본문

Frontend/React

React : useCallback (Hook)

ReasonJun 2023. 6. 13. 14:39
728x90

useCallback is a hook in React that is used to memoize and optimize the creation of a function, especially when passing that function down to child components. It is primarily used to avoid unnecessary re-creation of function references, which can lead to unnecessary re-renders of child components.

 

When a component renders, any functions defined within the component body are recreated each time the component re-renders, even if their dependencies have not changed. This can be problematic when passing functions as props to child components because it may cause those child components to re-render unnecessarily.

 

The useCallback hook helps address this issue by memoizing a function and returning a memoized version of it. The memoized version of the function is only re-created when the dependencies specified in the dependency array change.

 

Here's the basic syntax of useCallback:

const memoizedCallback = useCallback(callback, dependencies);
  • callback is the function that you want to memoize.
  • dependencies is an optional array of dependencies. The memoized function will only be re-created if any of the dependencies in the array change.

Here's an example to demonstrate the usage of useCallback:

import React, { useState, useCallback } from 'react';

const ChildComponent = React.memo(({ onClick }) => {
  console.log('ChildComponent rendered'); // Not work due to useCallback() in ParentComponent
  return <button onClick={onClick}>Click Me</button>;
});

const ParentComponent = () => {
  const [count, setCount] = useState(0);

  const handleClick = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, []); 
// No dependencies specified, so the memoized function is created once

  return (
    <div>
      <ChildComponent onClick={handleClick} />
      <p>Count: {count}</p>
    </div>
  );
};

export default ParentComponent;

In this example, we have a ParentComponent that renders a ChildComponent and displays a count. The handleClick function is defined within the ParentComponent and passed as a prop to ChildComponent.

 

By using useCallback, we ensure that the handleClick function is memoized and does not change on every re-render of the ParentComponent unless its dependencies (specified in the empty dependency array) change. This avoids unnecessary re-renders of the ChildComponent when the ParentComponent re-renders due to other unrelated changes.

 

The useCallback hook is particularly useful when dealing with expensive computations or when passing callback functions down to child components, as it can help optimize the performance of your React application by reducing unnecessary re-renders.

 

import React, { useCallback } from 'react';

const Message = React.memo(({ message }) => {
  return <p>{message}</p>;
});

const ListItem = React.memo(({ post }) => {
  return (
    <li key={post.id}>
      <p>{post.title}</p>
    </li>
  );
});

const List = React.memo(({ posts, testFunction }) => {
  console.log('List component rendered') // this not work
  return (
    <ul>
      {posts.map((post) => (
        <ListItem post={post} />
      ))}
    </ul>
  );
});

const B = ({ message, posts }) => {
  console.log('B component rendered') // only this work
  const testFunction = useCallback(() => {}, [])
  return (
    <div>
      <h1>B Component</h1>
      <Message message={message} />
      <List posts={posts} testFunction={testFunction}/>
    </div>
  );
};

export default B;
728x90

'Frontend > React' 카테고리의 다른 글

React : React Router Dom  (0) 2023.06.14
React : useMemo (Hook)  (1) 2023.06.13
React : Shallow / Deep compare  (0) 2023.06.13
React : Comparison method (React.memo: shallow , _isEqual: deep)  (0) 2023.06.13
React : React.memo (comparison method)  (0) 2023.06.13
Comments