해당 글은 프론트엔드를 공부하면서 기록 목적으로 작성한 내용입니다.
잘못된 내용이 있다면 제보 부탁드립니다. 🙇♂️
리액트의 내장 함수인 useState
를 사용하여 자식 컴포넌트에 state를 전달하려면 props로 내려야 한다.
만약, state가 자식의 자식의 자식에서 사용한다면 props를 내리고 또 내리고를 반복해야 하는 불편함이 발생한다.
redux는 전역 상태 관리를 편히 할 수 있게 해주는 라이브러리로 컴포넌트에 종속되지 않고, 상태 관리를 컴포넌트 밖에서 사용할 수 있다.
프로젝트 루트 레벨에서 store
라는 곳에 state를 저장하고, 모든 컴포넌트는 store에 구독을 하면서 state와 그 state를 바꾸는 함수를 어느 위치에 있든 상관 없이 상태를 받을 수 있게 된다.
store
에 들어갈 state와 함수를 정의하는 곳이다.불변성이란? 허락없이 데이터가 바뀌면 안된다는 의미로 리덕스에 저장된 데이터(state)는 마구잡이로 변하지 않도록 불변성을 유지해주어야 한다.
src/redux/modules/techInfo.js
// 액션 생성
const CREATE = 'techInfo/CREATE';
const DELETE = 'techInfo/DELETE'
// 초기값 설정
const initialState = {
list: [
{
id: 0,
author: "글쓴이A",
title: "0번째 게시글입니다.",
category: "HTML",
url: "http://www.naver.com",
content: "유용한거 같아서 공유합니다.",
created_date: new Date().toLocaleString(),
},
{
id: 1,
author: "글쓴이B",
title: "1번째 게시글입니다.",
category: "CSS",
url: "http://www.google.com",
content: "유용한거 같아서 공유합니다.",
created_date: new Date().toLocaleString(),
},
{
id: 2,
author: "글쓴이C",
title: "3번째 게시글입니다.",
category: "React",
url: "http://velog.io",
content: "react dom에 관한 글입니다.",
created_date: new Date().toLocaleString(),
},
],
};
// 액션 생성 함수
export function createTechInfo(techInfo) {
return {type: CREATE, techInfo: techInfo};
}
export function deleteTechInfo(techInfo_id) {
return {type: DELETE, techInfo_id};
}
//리듀서
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case "techInfo/CREATE": {
const new_techInfo_list = [...state.list, action.techInfo];
return {list: new_techInfo_list}
}
case "techInfo/DELETE": {
const new_techInfo_list = state.list.filter((l, idx) => {
return parseInt(action.techInfo_id) !== idx;
});
return {list: new_techInfo_list}
}
default: return state;
}
}```
src/redux/configStore.js
import { createStore, combineReducers } from "redux";
import techInfo from "./modules/techInfo";
const rootReducer = combineReducers({ techInfo });
const store = createStore(rootReducer);
export default store;
참고: 스파르타 코딩클럽 리액트 강의 및 리액트를 다루는 기술