728x90

리액트에서의 상태 관리 방법

  • 리액트(React)에서 상태 관리 방법에 대해 알아보자.
  • 리액트에서는 상태 관리를 위해 여러 가지 방법을 사용할 수 있으며, 상황에 따라 적절한 방법을 선택하는 것이 중요하다.

 

상태 관리 방법

1. 지역 상태(Local State)

  • 리액트의 useState 훅을 사용하여 컴포넌트 내부에서 상태를 관리할 수 있다.
  • 작은 규모의 애플리케이션이나 단일 컴포넌트에서 상태 관리가 필요한 경우 적합하다.
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

 

2. Context API

  • 리액트의 Context API를 사용하면 트리 구조의 깊은 컴포넌트 간에 상태를 공유할 수 있다.
    • @createContext@, @useContext@ 등을 사용한다.
  • 중간에 많은 컴포넌트들이 있을 때 Prop Drilling을 피할 수 있다.
import React, { createContext, useContext, useState } from 'react';

const CountContext = createContext();

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

function Counter() {
  const { count, setCount } = useContext(CountContext);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

function App() {
  return (
    <CounterProvider>
      <Counter />
    </CounterProvider>
  );
}

 

3. 리덕스(Redux)

  • 리덕스는 전역 상태 관리를 위한 라이브러리로, 애플리케이션의 모든 상태를 하나중앙 저장소(Store)에서 관리한다.
  • 상태가 복잡하고 많은 컴포넌트 간에 공유되어야 할 때 사용하면 좋다.
import { createStore } from 'redux';
import { Provider, useDispatch, useSelector } from 'react-redux';

// Reducer
const counterReducer = (state = { count: 0 }, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
};

// Store
const store = createStore(counterReducer);

// Counter component
function Counter() {
  const dispatch = useDispatch();
  const count = useSelector((state) => state.count);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>
        Click me
      </button>
    </div>
  );
}

function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

 

4. 리코일(Recoil)

  • 리코일은 페이스북에서 만든 상태 관리 라이브러리로, 리액트의 상태 관리를 더 간편하게 해준다.
  • 전역 상태와 비슷하지만, 더 세밀하게 상태를 관리할 수 있다.
import { atom, selector, useRecoilState, useRecoilValue } from 'recoil';

const countState = atom({
  key: 'countState',     // 고유값 ID 
  default: 0,            // 기본값(초기값)
});

function Counter() {
  const [count, setCount] = useRecoilState(countState);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

function App() {
  return (
    <RecoilRoot>
      <Counter />
    </RecoilRoot>
  );
}

 

5. MobX

  • MobX는 리액티브 상태 관리를 제공하는 라이브러리로, 상태가 변할 때마다 자동으로 UI가 업데이트된다.
  • 코드가 간결하고 직관적이며, 상태 변화에 따른 부수 효과(Side Effect)를 쉽게 관리할 수 있다.
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react';

class CounterStore {
  count = 0;

  constructor() {
    makeAutoObservable(this);
  }

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

const counterStore = new CounterStore();

const Counter = observer(() => (
  <div>
    <p>You clicked {counterStore.count} times</p>
    <button onClick={() => counterStore.increment()}>Click me</button>
  </div>
));

function App() {
  return <Counter />;
}

 

 

 

728x90