React

[React Redux] React에 Redux 적용하기

hazel__ 2022. 6. 3. 00:06

이전에는 전역 변수의 관리를 위해 React context를 사용했다면, 이번에는 Redux를 사용하려고 한다.

React와 typescript 환경에서 코드를 작성하고 있다!

 

Redux란?


리덕스는 action 이벤트를 사용하여 어플리케이션 상태를 관리하고 업데이트하는 라이브러리이다.

전체 어플리케이션에서 상태에 접근할 수 있는 특징이 있어 전역 변수를 관리할 수 있다.

즉, 해당 값이 필요한 컴포넌트에 도달하기 위해서 거치는 모든 자식 컴포넌트에 매개변수로 값을 전달하지 않고, 값이 필요한 컴포넌트에서만 참조하여 사용할 수 있다.

https://react-redux.js.org/

 

React Redux | React Redux

Official React bindings for Redux

react-redux.js.org

 

React-Redux

npm install redux react-redux 

 

API


Provider

Provider 컴포넌트를 사용해서, 해당 컴포넌트의 하위 컴포넌트에서 Redux store 를 사용할 수 있다.

//main.tsx
import { configureStore } from "@reduxjs/toolkit";
import { Provider } from "react-redux";
import lentReducer from "./lentReducer";

const store = configureStore({reducer: lentReducer});
store.subscribe(()=>{console.log("subscribe = ", store.getState())});

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>
  document.getElementById("root")
);

 

Store

configureStore 함수를 사용하여 store를 생성한다.

이때, store는 어플리케이션의 전체적인 상태 트리를 말하고, 일부 메서드를 포함하는 객체(object)다.

getState

어플리케이션의 현재 상태 트리를 반환한다. 이는 store의 reducer의 반환 값과 동일하다.

dispatch(action)

action을 dispatch하는 함수이다. state를 바꿀 수 있는 유일한 방법이다.

subscribe(listener)

action이 dispatch 될 때마다 listener가 실행된다.

replaceReducer(nextReducer)

현재 사용하는 reducer를 nextReducer로 대체한다.

 

 

Hooks


React Redux는 useSelector, useDispatch 훅을 제공하며, 이를 이용해서 React 컴포넌트가 Redux store와 상호작용할 수 있다.

useSelector

useSelector는 store 에 저장된 값을 읽어올 수 있고, 값의 변화를 구독(subscribe)한다.

즉, store에 저장된 값에 변화가 생기면, 해당 값을 사용한 컴포넌트가 리렌더된다.

//Lent.tsx
import { useSelector } from "react-redux";

const Lent = () => {
	const lentInfo = useSelector((state: RootState) => state.lent);

	return (
		<div>{lentInfo.name}</div>
	);
}

 

useDispatch

useSelector가 store에 저장된 값을 불러온다면, useDispatch는 store에 값을 저장한다.

useDispatch는 store의 dispatch를 반환하고, 이를 사용하여 dispatch actions를 실행할 수 있다.

dispatch가 생소하다면, React useReducer를 참조하면 된다!

//Lent.tsx
import { useSelector, useDispatch } from "react-redux";
import { initializeLent } from "./lentReducer"

const Lent = () => {
	const dispatch = useDispatch();
	const lentInfo = useSelector((state: RootState) => state.lent);

	if (lentInfo === undefined) {
		dispatch(initializeLent());
	}

	return (
		<div>{lentInfo.name}</div>
	);
}

Reducer 함수를 정의한다.