React 상태 관리

zion·2023년 9월 17일
0

React

목록 보기
1/8

props-drilling: 부모 컴포넌트에서 특정 자식 컨포넌트로 데이터가 이동하는 과정으로, 데이터를 전달만 하는 컴포넌트가 존재하게 된다.

props-drilling 을 막는 방법

  • React Context API.
  • Composition
  • Render props
  • HOC : 컴포넌트를 인자로 받아 새로운 컴포넌트로 변환해 반환하는 함수
  • 상태관리 라이브러리: Redux,Recoil,React-Query...

1) React Context API.

  • React 의 내장 기능
  • 중소규모의 어플리케이션 또는 특정 부분을 관리하는데에 사용
import React, { createContext, useContext, useState } from 'react';

const CounterContext = createContext();

function CounterProvider({ children }) {
  const [count, setCount] = useState(0);
  return (
    <CounterContext.Provider value={{ count, setCount }}>
      {children}
    </CounterContext.Provider>
  );
}

function useCounter() {
  return useContext(CounterContext);
}

2) Redux

  • 중앙집중식 store, 상태 변화를 다루는 reducers, 변화에 트리거되는 actions
  • 단방향
  • 큰 미들웨어 생태계와 개발자 툴이 있다.
import { createStore } from 'redux';

const initialState = {
  count: 0,
};

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
}

const store = createStore(counterReducer);

3) Mobx

  • 단순하고 확장 가능하다.
  • observable 와 action 으로 상태 업데이트를 자동으로 관리한다.
  • Redux 보다 유연하고 less boilerplate-heavy
import { observable, action } from 'mobx';

class CounterStore {
  @observable count = 0;

  @action
  increment() {
    this.count++;
  }
}

const counterStore = new CounterStore();

4) Recoil

  • facebook에서 개발
  • 대규모 어플리케이션에서 더 나은 성능 제공
  • atom 과 selector 사용
  • React 와 유사한 접근 방식
import { atom, selector, useRecoilState, useRecoilValue } from 'recoil';

const countState = atom({
  key: 'countState',
  default: 0,
});

const incrementState = selector({
  key: 'incrementState',
  set: ({ set }) => {
    set(countState, (count) => count + 1);
  },
});

function Counter() {
  const [count, setCount] = useRecoilState(countState);
  const increment = useRecoilValue(incrementState);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(increment)}>Increment</button>
    </div>
  );
}

5) React-Query

  • fetch or axios 대신 useQuery 사용
  • 자동 캐싱
  • 실시간 업데이트
  • Client/Server 데이터 분리 가능
// Without React Query
fetch('/api/data').then(response => response.json()).then(data => ...);

// With React Query
const { data } = useQuery('data', () => fetch('/api/data')
                      .then(response => response.json())
                  );
  • 페이징, 무한스크롤 구현 지원
const { data, fetchNextPage } = useInfiniteQuery(['items'], fetchPageData);

출처:

https://medium.com/analytics-vidhya/props-drilling-in-react-js-934120a4906b
https://medium.com/@AlexanderObregon/comparing-redux-with-alternative-state-management-solutions-mobx-context-api-and-recoil-7694091dd87c
https://medium.com/@kvs.sankar23/react-query-is-the-best-thing-that-happened-to-react-abd92553e953

profile
be_zion

0개의 댓글