🙆♂️ redux 설치
npm install redux react-redux
위 코드로 redux와 react-redux를 설치합니다.
🙋♂️ redux 사용
import { createStore } from 'redux';
const store = createStore();
먼저 store를 만들어줍니다.
그리고 reducer가 필요합니다.
function reducer(currentState, action){
if(currentState === undefined){
return{
number:1
}
}
const newState = {...currentState};
return newState
}
여기서 reducer 함수의 인자값인 currentState값은 현재 state 값이고
action은 어떻게 바꿀지에 대한 요청 값입니다.
이 값을 return 해주면 새로운 state 값으로 되는 것입니다.
그리고 불변해야 하기 때문에
const newState = {...currentState};
이 명령어를 통해서 새로운 newState에 currentState값을 복사해서 넣습니다. 이렇게 변화시킨 State를 return하는 것입니다.
그리고 만약 State 값이 정의 되있지 않다면
if(currentState === undefined){
return{
number:1
}
}
if문으로 undefined인 것을 거르고 state값을 정의하여 return합니다.'
마지막으로 생성했었던 store 변수에 reducer를 연동시켜줍니다.
const store = createStore(reducer);
import { createStore } from 'redux';
import { Provider } from 'react-redux';
function reducer(currentState, action){
if(currentState === undefined){
return{
number:1
}
}
const newState = {...currentState};
return newState
}
const store = createStore(reducer);
현재까지 Redux 코드는 이렇습니다.
const number = 1;
function reducer(state=number, action){
return state
}
이런식으로도 사용 가능. 이 코드와 위 코드는 같지만 useSelector를 쓸 때 달라짐.
🚀Provider
Provider를 통해서 redux를 사용할 컴포넌트를 정의합니다.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>
);
저같은 경우 index.js에서 이렇게 정의했습니다.
그러면 App.js 안에 있는 모든 컴포넌트에서 사용할 수 있습니다.
참고로 Provider의 속성값으로 store 속성이 필수적입니다.
🚀useSelector
const number = useSelector((state)=>state.number);
이렇게 state.number를 불러와서 number 변수애 넣어서 원하는 곳에 이 state를 사용할 수 있습니다.
const number = useSelector((state)=>state);
2번째로 소개한 코드로 reducer를 만들었으면 이렇게 해야합니다.
🚀useDispatch
function reducer(currentState, action){
if(currentState === undefined){
return{
number:'1'
}
}
const newState = {...currentState};
if(action.type === 'ONE'){
newState.number += '1'
}
return newState
}
이렇게 if문으로 action.type을 지정해주면 그 타입을 통해서
import { useDispatch } from "react-redux";
<button className='btn-num' onClick={()=>dispatch({
type:'ONE'
})}>1</button>
이런식으로 dispatch 를 사용해서 state를 변경할 수 있습니다.
'웹 개발 > React 공부' 카테고리의 다른 글
[React] 06. Material UI Icon 사용법 초초 간단 소개 (0) | 2022.07.26 |
---|---|
[React] 05. props (0) | 2022.07.25 |
[React] 04. 컴포넌트 - Component (0) | 2022.07.14 |
[React] 03. 버튼 - Button / state 변경(array) (0) | 2022.07.07 |
[React] 02. State 사용 (0) | 2022.07.07 |