// 리액트를 다루는 기술 16장
리덕스란? 가장 많이 사용하는 리액트 상태 관리 라이브러리
장점
자세한 코드는 깃헙 참조!
https://github.com/juhui88/ReactStudy/blob/master/vanilla-redux/index.js
GitHub - juhui88/ReactStudy
Contribute to juhui88/ReactStudy development by creating an account on GitHub.
github.com
상태에 어떠한 변화가 필요할 때 액션이라는 것이 발생(객체로 표현)
이런 액션 객체를 만들어 주는 함수가 액션 생성 함수이다
// 액션 이름
// 액션 이름은 문자열 형태로 주로 대문자로 작성하고 그 이름은 고유해야 함(중복되지 않아야)
const TOGGLE_SWITCH = "TOGGLE_SWITCH";
const INCREASE = "INCREASE";
const DECREASE = "DECREASE";
// 액션 생성 함수
const toggleSwitch = () => ({
type: TOGGLE_SWITCH // type 필드 필수, 이 값을 액션의 이름이라 생각하면 됨
});
const increase = (difference) => ({
type: INCREASE,
difference // 그 외의 값은 상태 업데이트 시 참고할 값으로 작성자 마음대로 넣을 수 있음
});
const decrease = () => ({
type: DECREASE
});
: 변화를 일으키는 함수
리듀서 함수는 현재 상태(state)와 전달받은 액션 객체(action)를 참고하여 새로운 상태를 만들어 반환한다
// 리듀서 함수 정의
// state가 undefined일 때는 initialState를 기본값으로 사용
function reducer(state = initialState, action) {
switch (action.type) { // action.type에 따라 다른 작업 처리
case TOGGLE_SWITCH:
return {
...state, // 불변성
toggle: !state.toggle
};
case INCREASE:
return {
...state, // 불변성
counter: state.counter + action.difference
};
case DECREASE:
return {
...state, // 불변성
counter: state.counter - 1
};
default:
return state;
}
}
리덕스를 적용하기 위해 필요한 것으로 createStore 함수를 사용함
한 개의 프로젝트는 단 하나의 스토어만 가질 수 있으며 스토어 안에는 현재 애플케이션 상태와 리듀서가 들어가 있다
함수의 파라미터에는 리듀서 함수를 넣어주어야 한다
import { createStore } from 'redux';
...
const store = createStore(reducer);
: 스토어 내장 함수 중 하나로 subscribe 함수 안에 리스너 함수를 파라미터로 넣어서 호출해 주면, 이 리스너 함수가 액션이 디스패치되어 상태가 업데이트 될 때마다 호출됨
...
// Render 함수 만들기
const render = () => {
const state = store.getState(); // 현재 상태 부르기
// 토글 처리
if (state.toggle) {
divToggle.classList.add("active");
} else {
divToggle.classList.remove("active");
}
// 카운터 처리
counter.innerText = state.counter;
};
render();
store.subscribe(render); // 상태가 업데이트 될 때마다 render 함수 호출
현 프젝에서는 subscribe 함수를 사용하지만 추후 리액트 프젝에서 리덕스를 사용할 땐 이걸 사용 안 할거임
리액트에서는 react-redux라는 라이브러리가 이를 대신해 줄 것임
: 스토어 내장 함수 중 하나로 액션을 발생시키는 함수
dispatch(action)과 같은 형태로 액션 객체를 파라미터로 넣어서 호출
이 함수가 호출되면 스토어는 리듀서 함수를 실행시켜서 새로운 상태를 만들어줌
...
// 액션 발생시키기
divToggle.onclick = () => {
console.log("divToggle click");
store.dispatch(toggleSwitch());
};
btnIncrease.onclick = () => {
console.log("btnIncrease click");
store.dispatch(increase(1));
};
btnDecrease.onclick = () => {
console.log("btnDecrease click");
store.dispatch(decrease());
};
[React] ThemeProvider (0) | 2022.07.09 |
---|---|
[React] Typescript로 React 작성하기 (0) | 2022.07.06 |
[React] styled-components (0) | 2022.06.15 |
[React] React Router 사용하기 (0) | 2022.06.13 |
[React] API 호출하기 (0) | 2022.06.13 |