useCallback

홍준섭·2023년 3월 1일

react

목록 보기
13/29

useCallback

useCallback은 리렌더링 간에 함수 정의를 캐시할 수 있는 React Hook이다.

useCallback(fn,dependencies)

매개변수

  • fn: 캐시하려는 함수 값이다. 모든 인수를 취하고 모든 값을 반환할 수 있다. React는 초기 렌더링 중에 함수를 반환한다(호출X). React는 함수를 호출하지 않는다. 함수가 반환되므로 언제 호출할지 여부를 결정할 수 있다.
  • dependencies: 코드 내부에서 참조되는 모든 반응 값 목록이다.

용법

구성 요소의 리렌더링 건너뛰기

import { useCallback } from 'react';

function ProductPage({ productId, referrer, theme }) {
  const handleSubmit = useCallback((orderDetails) => {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails,
    });
  }, [productId, referrer]);
  // ...

useCallback과 useMemo의 차이

  • useMemo는 함수 호출 결과를 캐시하고 useCallback은 함수 자체를 캐시한다

메모화된 콜백에서 상태 업데이트

function TodoList() {
  const [todos, setTodos] = useState([]);

  const handleAddTodo = useCallback((text) => {
    const newTodo = { id: nextId++, text };
    setTodos(todos => [...todos, newTodo]);
  }, []); // ✅ No need for the todos dependency
  // ...

Effect가 너무 자주 발생하지 않도록 방지

function ChatRoom({ roomId }) {
  const [message, setMessage] = useState('');

  const createOptions = useCallback(() => {
    return {
      serverUrl: 'https://localhost:1234',
      roomId: roomId
    };
  }, [roomId]); // ✅ Only changes when roomId changes

  useEffect(() => {
    const options = createOptions();
    const connection = createConnection();
    connection.connect();
    return () => connection.disconnect();
  }, [createOptions]); // ✅ Only changes when createOptions changes
  // ...

custom hook 최적화

function useRouter() {
  const { dispatch } = useContext(RouterStateContext);

  const navigate = useCallback((url) => {
    dispatch({ type: 'navigate', url });
  }, [dispatch]);

  const goBack = useCallback(() => {
    dispatch({ type: 'back' });
  }, [dispatch]);

  return {
    navigate,
    goBack,
  };
}
profile
개발 공부중입니다

0개의 댓글