포스코x코딩온 웹 풀스택 양성과정

[포스코x코딩온] 웹 풀스택 과정 12주차 회고 | Hook (useMemo, useCallback, useReducer)

Codult 2024. 4. 5. 15:12
728x90

 

💡 useMemo

  • 렌더링 과정에서 특정 값이 바뀌었을 때만 연산을 실행한다.
const memoizedValue = useMemo(callback, dependency);
// 두 번째 인자로 받은 의존배열(dependency) 내 값이 바뀌는 경우에만,
// 첫번째 인자로 받은 콜백함수를 실행하여, 구한 값을 반환함
  • 해당 값이 변하지 않았는데 리렌더링 될 때, 메모리에 저장해두었던 결과값을 재사용한다. (성능 최적화)
import { useMemo, useState } from 'react';

export default function UseMemo() {
  const [count, setCount] = useState(0);
  const [inputValue, setInputValue] = useState("");
 
  const calc = useMemo(() => {
    return count * 2;
  }, [count])
  // count가 변할 때만 연산 수행됨
  
  return (
    <>
      <input value={inputValue} onChange={(e) => setInputValue(e.target.value)}/>
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
      <p>Count: {count}</p>
      <p>Doubled Count: {calc}</p>
    </>
  )
}


💡 useCallback

  • 리렌더링될 때, 함수를 다시 불러오는 것을 막는다.
  • 콜백함수의 의존성이 변경되었을 때에만, 함수를 새로 생성한다. (변경되지 않은 경우에는 기존 함수를 계속 반환함)
import { useCallback, useState } from 'react';

export default function UseCallback() {
  const [count, setCount] = useState(0);
  // 일반 함수
  const increment = () => {
    setCount((prevCount) => prevCount + 1);
  };
  // useCallback
  const incrementCount = useCallback(() => {
    console.log("count:", count);
    setCount((prevCount) => prevCount + 1);
  }, []);
  // 처음 만들어둔 함수를 사용하기 때문에, 콘솔 창에 출력되는 count 값이 변하지 않음
  
  return (
    <>
      <button onClick={increment}>Increment</button>
      <button onClick={incrementCount}>Increment count</button>
      <p>Count: {count}</p>
    </>
  )
}


💡 useReducer

  • '현재 상태'와 업데이트를 위해 필요한 정보를 담은 '액션 값'을 전달 받아, 새로운 상태를 반환하는 함수이다.
const [state, dispatch] = useReducer(reducer, initialState);
// state: 현재 상태
// dispatch: 액션을 발생시키는 함수
// (액션 값을 전달받아, state와 함께 reducer로 전달한다.)
// reducer: state를 업데이트하는 함수
// initialState: 초기값 설정
import { useReducer } from "react";

const initialState = { count: 0 };
function reducer(state, action) {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
    default:
      throw new Error("Invalid action type");
  }
}

export default function UseReducer() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <>
      <p>Count: {state.count}</p>
      <button
        onClick={() => {
          dispatch({ type: "INCREMENT" });
        }}
      >INCREMENT</button>
      <button
        onClick={() => {
          dispatch({ type: "DECREMENT" });
        }}
      >DECREMENT</button>
    </>
  );
}
  • state가 단순하다면 useState() 사용, state가 복잡하다면 useReducer() 사용하는 것이 좋다.
728x90