What is Redux
Redux는 Actions이라 불리는 이벤트를 통해 상태관리 라이브러리이자 패턴이다.
Redux는 중앙집권화된 store를 통해 어플리케이션 전역상태를 관리하는 방식이다.
Why Should I Use Redux?
일반적으로 컴포넌트에서 props를 통해 데이터를 자식 컴포넌트에게 넘겨주는데
자식의 자식의 자식의 자식의 자식의 자식의 자식...
이런 과정이 백 번 반복되어서 데이터를 전달해줘야한다면,,?
전역 변수처럼 사용할 수 있는 데이터들이 있다면 이러한 문제가 쉽게 해결되지 않을까라는 것에서 기인한 것입니다.
Redux Flow
Redux Store
Redux Store는 내 어플리케이션의 전역 상태를 가지고 있는 유일한 컨테이너입니다.
Store는 하나의 오브젝트와 몇가지 기능을 가진 함수로 구성되어 있습다.
여기서 Store에 있는 전역변수들은 우리가 useState 변수들을 특정 Set함수들을 통해 변경하던 것처럼
특별한 동작(action)에 의해서만 변경할 수 있습니다.
Store → UI
Store에서 UI 방향 데이터 바인딩은
// Our "user interface" is some text in a single HTML element
const valueEl = document.getElementById('value')
// Whenever the store state changes, update the UI by
// reading the latest store state and showing new data
function render() {
const state = store.getState()
valueEl.innerHTML = state.value.toString()
}
// Update the UI with the initial data
render()
// And subscribe to redraw whenever the data changes in the future
store.subscribe(render)
다음과 같은 일련의 과정을 거칩니다.
- .getState() 메소드를 통해 상태값을 받아옵니다.
- .subscritbe(func()) 메소드를 통해 data가 변할 때 마다 UI를 다시 그립니다.
UI → Store
UI 에서 Store
document.getElementById('increment').addEventListener('click', function () {
store.dispatch({ type: 'counter/incremented' })
})
document.getElementById('decrement').addEventListener('click', function () {
store.dispatch({ type: 'counter/decremented' })
})
- .dispathch({ type: ‘reducer’action’}) dispathch라는 Method를 통해 Reducer func에 정의된 action.type을 Store에 전달합니다.
- Store는 전달받은 action을 가장 최근 State와 결합해 Reducer 함수에 넣어 새로운 상태를 업데이트 합니다
- 업데이트된 상태는 subscribe 메소드를 통해 다시 UI에 반영됩니다.
Redux 기반, Part 1: Redux Overview | Redux
The official Fundamentals tutorial for Redux: learn the fundamentals of using Redux
ko.redux.js.org
'Web > ReactJS' 카테고리의 다른 글
React, 절대 경로 설정 (Vite 기준) (0) | 2025.02.28 |
---|---|
React, 절대 경로 import (1) | 2024.10.28 |
ReactJS, Reducer (0) | 2024.07.31 |
React, Component란 (0) | 2024.07.26 |
React, JSX 문법 (1) | 2024.07.26 |