[Redux] Redux란?

bin·2023년 3월 21일
0

Redux란?

Redux는 자바스크립트 상태 관리 라이브러리입니다. 프로젝트 규모가 커질수록 컴포넌트 간 state를 공유할 필요성이 높아지는데요. 그럴 때마다 props로 state를 전달하기에는 무리가 있습니다. (props drilling)
이러한 문제를 해결하고자 등장한 것이 바로 Redux 입니다.
Redux를 사용하면 상태 관리 로직을 컴포넌트와 분리시킴으로써 보다 효율적으로 상태를 관리할 수 있습니다.

props drilling 이란?

(최상위노드) A-B-C-D (최하위노드) 컴포넌트가 있다고 생각해보자. 특정 props를 A 컴포넌트에서 D 컴포넌트로 전달해야 할 때, 항상 B-C를 거쳐서 전달한다면 매우 비효율적일 것이다. 이러한 문제를 Props drilling 이라고 칭한다. 바로 이 Props drilling 을 해결해주는 것이 Redux이다.

Reducer / Action

slice를 만들기 위해 slice를 식별할 수 있는 문자열, 상태의 초깃값, 상태를 업데이트할 수 있는 Reducer 함수를 작성합니다.

이렇게 slice를 만들고 난 후, Redux 액션 생성자와 전체 slice에 대한 Reducer 함수를 export 합니다.

// counterSlice.js
import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
	name: "counter",
  	// 초깃값
  	initialState: 0
  	// 리듀서
  	reducers: {
    	// 액션
 		add(state) {
    		return state + 1;
    	}
  	}
});

export const { add } = counterSlice.actions;
export default counterSlice.reducer;

Store

store란 의미 그대로 상태들의 보관 장소라고 생각하면 이해하기 쉽습니다. 컴포넌트별로 상태를 관리하지 않고, 컴포넌트 구조 외부에 하나의 store를 두어 그 곳에서 전역으로 관리할 수 있습니다.

counterSlice의 리듀서 함수를 store의 Reducer 매개변수 내부 필드로 작성하여 해당 상태의 모든 업데이트를 처리하도록 합니다.

// store.js
import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "../counterSlice";

const store = configureStore({
  reducer: {
    counter: counterSlice
  }
});

export default store;

React 컴포넌트에서 Redux state와 Action 사용하기

import { useDispatch } from 'react-redux' 
import { add } from './counterSlice'

export default function CounterContainer = () => {
  const count = useSelector((state) => { return state.counter })
  const dispatch = useDispatch(); 
	return (
    	<button onClick={() => {dispatch(add())}}>+</button>
        <span>{count}</span>
	)
}

useSelector: 현재 store에 저장된 상태값을 가져올 수 있는 Hook
useDispatch: 컴포넌트에서 dispatch 함수의 괄호 내부 action을 호출하여 상태값을 업데이트 시키는 Hook

0개의 댓글