ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • useCallback();
    React/react 2023. 7. 19. 13:25

    기록

    useCallback 이란?

     

    useCallback을 handleUpdate 함수에 넣지 않았더라면 Button 컴포넌트에서 onClick 이벤트가 발생할 때마다

    AppMentor 함수가 재랜더링 됐을 것이다.

    하지만 useCallback 를 사용하고 디펜던시를 넣어줌으로서 디펜던시에 있는 값들에 변화가 있을 시에만 재랜더링을 해주도록 하였다.

    아래 코드에서는 따로 디펜던시 값이 필요 없었기 때문에 빈 배열 '[ ]' 값을 주었다.

     

    import React, { memo, useCallback, useMemo, useReducer } from 'react';
    import personReducer from './reducer/person-reducer';
    
    export default function AppMentor() {
      const [person, dispatch] = useReducer(personReducer, initialPerson);
      
      const handleUpdate = useCallback(() => {
        const prev = prompt('누구의 이름을 바꾸고 싶은가요?');
        const current = prompt('이름을 무엇으로 바꾸고 싶은가요?');
    
        dispatch({type: 'updated', prev, current});
      }, []);
      return (
        <div>
          <h1>
            {person.name}는 {person.title}
          </h1>
          <p>{person.name}의 멘토는:</p>
          <ul>
            {person.mentors.map((mentor, index) => (
              <li key={index}>
                {mentor.name} ({mentor.title})
              </li>
            ))}
          </ul>
          <Button text='멘토 바꾸기' onClick={handleUpdate} />
        </div>
      );
    }
    
    const Button = memo(({ text, onClick }) => {
      console.log('Button', text, 're-rendering 😜');
      const result = useMemo(() => calculateSomething(), []);
      return (
        <button
          onClick={onClick}
          style={{
            backgroundColor: 'black',
            color: 'white',
            borderRadius: '20px',
            margin: '0.4rem',
          }}
        >
          {`${text} ${result}`}
        </button>
      );
    });
    
    function calculateSomething() {
      for (let i = 0; i < 1000; i++) {
        console.log('😆');
      }
      return 10;
    }
    
    
    
    const initialPerson = {
      name: '앙꼬',
      title: '개발자',
      mentors: [
        {
          name: '밥',
          title: '시니어개발자',
        },
        {
          name: '제임스',
          title: '시니어개발자',
        }
      ]
    };

     

     

     

     

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

    react-router-dom  (0) 2023.12.05
    custom hooks / useQuery(tanstack/react-query)  (0) 2023.07.24
    Context 란?  (0) 2023.07.24

    댓글

Designed by Tistory.