티스토리 뷰

컴포넌트 단위로 나눌 수 있는 만큼 나눠야 나중에 성능최적화 하기 편리


useReducer

state의 갯수를 줄임, state 통일

state가 비동기적으로 바뀜

...

const initialState = {
  winner: '',
  turn: 'O',
  tabalData: [['','',''], ['','',''], ['','','']],
}

const reducer = (state, action) => { // reducer = 함수 state와 action을 인자로 받음
  switch (action.type) { // action을 받아와서 실행
    case 'SET_WINNER' :
      return {
        ...state, // state를 직접 바꾸면 안됨 state.winner = action.winner; (X)
        winner: action.winner,
      }
  }
}

const TicTacToe = () => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const { tableData, turn, winner, recentCell } = state;
  // 자식 컴포넌트가 여러개 있음, 이렇게 하면 state가 너무 많아짐
  // const [winner, setWinner] = useState('');
  // const [turn, setTurn] = useState('O');
  // const [tableData, setTableData] = useState([['','',''], ['','',''], ['','','']]);

  const onClickTable = useCallback(() => { // 함수에는 useCallback
    dispatch({type: 'SET_WINNER', winner: 'O'}) // dispatch 안에 들어가는 건 action이라고 함, Redux에서 따옴
  }, []); // {액션 객체}를 dispatch(=실행)함 > 액션을 해석하고 state를 바꿔주는 역할을 reducer가 함
  ...생략

state를 하나로 모아두고 action을 통해서만 값을 바꿔줌

객체가 action이고 type은 action의 이름(action의 이름은 보통 대문자로 함)이고 나머지는 데이터

action을 dispatch하면 action이 실행되고 > 실행이 되면 reducer에 정의해둔대로 state를 바꿈

state를 바꿀 때는 불변성에 주의하면서 바꿀 것

 


성능최적화 할 때 어디서 렌더링이 발생하는지 잘 모르겠을 때 알아내기

  const ref = useRef([]); // ref 사용
  useEffect(()=>{
    console.log(rowIndex === ref.current[0], cellIndex === ref.current[1], dispatch === ref.current[2], cellData === ref.current[3]); // 어떤 값이 바뀌었는지 알아내기
    ref.current = [rowIndex, cellIndex, dispatch, cellData];
  }, [rowIndex, cellIndex, dispatch, cellData]);

리렌더링을 막기 위해 memo 사용! 반복문이 있을 때 사용하면 좋음

 

최후의 수단 useMemo

기본식은 useEffect와 같음, 컴포넌트 자체를 기억

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함