react에서 상태를 관리하기 위해서는 보통
useState()
를 이용한다
react에서 상태를 다른 컴포넌트에 전달하는 경우에는 props를 통해 상태를 전달하는데,
바로 하위 컴포넌트는 상관이 없지만 만약 하위 컴포넌트가 10만개라면 props를 10만번 내려줘야한다
이런 비효율적인 상황에서 필요한 경우 한 곳에서 상태를 관리하고, 필요한 컴포넌트로 직접 전달해준다면 얼마나 효율적일까?
기본적으로 React-Redux는 React에서 상태관리를 위해 사용하는 모듈이다
☼ React 뿐만아니라 일반 JavaScript에서도 사용가능한 Redux도 있다
- 📌 React-Redux의 자세한 내용은 공식사이트에서 확인 가능하다
설치
npm install @reduxjs/toolkit react-redux
// counterReducer.js
const INCRESE = "INCRESE";
const DECRESE = "DECRESE";
export const increse = () => {
return{
type:INCRESE
}
}
export const decrese = () => {
return{
type:DECRESE
}
}
const initialState: {
value: 0,
},
export default const counter = (state=initialState, action) => {
switch (action.type) {
case INCRESE :
return {...state, value++}
case DECRESE :
return {... state, value--}
default :
return state;
}
}
counter
는 store파일
로 보내질 예정이고 다른 함수들은 실제로 Dispatch()
를 이용해 사용할 예정이다!// store.js
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../counterReducer'
export default configureStore({
reducer: {
counter: counterReducer,
},
})
//index.js
import React from "react";
import { Provider } from "react-redux";
import store from './store'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
index.js
에서 react-redux의 Provider를 이용해 을 감싸고 store에는 우리가 종합한 store를 넣어준다import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { decrese, increse } from './counterReducer'
export function Counter() {
const value = useSelector((state) => state.value)
const dispatch = useDispatch()
return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => dispatch(increse())}
>
Increment
</button>
<span>{value}</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrese())}
>
Decrement
</button>
</div>
</div>
)
}
useSelector
를 이용하고, 상태를 변경하기 위한 함수는 useDispatch()
를 이용한다여기까지 간단하게
React-Redux
에 대해 알아보았는데React
를 사용하는데 아쉬운점을 제대로 보안해줄 수 있는 유용한 기술이라고 생각한다 😀