리덕스는 리액트에서 컨포넌트가 많아지고 복잡해지면서 생기는 복잡한 prop를 관리하기 위한 라이브러리/패턴이다.
리덕스를 사용하면 액션시 스토어가 포함된 컨포넌트만 재랜더링 되기 때문에 퍼포먼스면에서 더 효율적이다.
createSrote를 사용하는 과정에서 Reduxjs/toolkit을 권장하고 있기에 밑줄이 계속 발생했다. 아직은 createStore을 사용할 수 있으나, toolkit을 설치 후 configureStore를 사용하거나 legacy_createStore as createStore로 사용해야 함.
import * as React from 'react';
import './style.css';
import { legacy_createStore as createStore } from 'redux';
// reduxjs/toolkit 에서는 configureStore를 추천하지만,
// createStore를 계속 사용하기 위해 legacy_createStore as createStore를 씀
import { Provider, useSelector, useDispatch, connect } from 'react-redux';
function reducer(currentState, action) {
if (currentState === undefined) {
return {
number: 1,
};
}
// 각각의 스테이트 값의 변화를 불변하게 유지해야함.
const newState = { ...currentState };
if (action.type === 'PLUS') {
newState.number++;
}
return newState;
}
const store = createStore(reducer);
export default function App() {
// const [number, setNumber] = React.useState(1);
return (
<div id="container">
<h1>Root</h1>
<div id="grid">
<Provider store={store}>
<Left1 />
<Right1 />
</Provider>
</div>
</div>
);
}
function Left1(props) {
return (
<div>
<h1>Left1</h1>
<Left2 />
</div>
);
}
function Left2(props) {
console.log('2');
return (
<div>
<h1>Left2</h1>
<Left3 />
</div>
);
}
// redux를 사용하면 state를 사용하는 넘버만 재랜더링 된다.
// 퍼포먼스면에서 효율적임.
function Left3(props) {
console.log('3');
const number = useSelector((state) => state.number);
// useSelector는 함수를 인자로 받음
return (
<div>
<h1>Left3 : {number}</h1>
</div>
);
}
function Right1(props) {
return (
<div>
<h1>Right1</h1>
<Right2 />
</div>
);
}
function Right2(props) {
return (
<div>
<h1>Right2</h1>
<Right3 />
</div>
);
}
function Right3(props) {
const dispatch = useDispatch();
return (
<div>
<h1>Right3</h1>
<input
type="button"
value="+"
onClick={() => {
dispatch({ type: 'PLUS' });
}}
/>
</div>
);
}
// 부모 자식 컴포넌트가 많아지고 복잡해 질 때, props 관리 또한 복잡해 진다.
https://stackblitz.com/edit/react-ts-2itycz?embed=1&file=App.tsx
React Ts (forked) - StackBlitz
stackblitz.com
https://www.youtube.com/watch?v=yjuwpf7VH74&t=40s
728x90
'Frontend > React' 카테고리의 다른 글
틱택톡 실습 with 공식문서 (0) | 2022.06.15 |
---|---|
Next.js 배우기 시이이이작! (0) | 2022.05.21 |
Redux 복습 with 공식문서 2 (0) | 2022.05.11 |
Redux 복습 with 공식문서 1 (0) | 2022.05.11 |
React Life Cycle (0) | 2022.03.03 |