STUDYING/Redux
[Redux] 리덕스 기초
sustronaut
2022. 6. 19. 20:10
1. 리덕스 왜 필요할까?
- 상단에서 제일 말단까지 전해지는 과정이 매우 번거롭다.
- 말단까지 가는 데 일억개의 단계가 필요하다면 매우 시간이 오래걸리고 좋은 코드가 아니다.
=> 이 점을 극복하기 위해 리덕스로 개발
2. 리덕스 설치
npm install redux react-redux
- react-redux는 react와 redux가 서로 독립적이기 때문에 이 둘을 연결시켜주는 기능이다.
3. reducer
- storage안에 있는 state를 어떻게 바꿀 거인가를 결정
- 리덕스 사용하는데 있어서 무조건 사용해야함
import { createStore } from 'redux';
function reducer(currentState, action){
if(currentState === undefined ) { //현재 state가 정해지지 않았다면 기본 state를 리턴해줌
return {
number: 1, //number라는 state값의 기본이 1이다
}
}
const newState = {...currentState} // 과거의 state 복제해옴 -> 복제본을 수정하면 불변성 유지 가능
return newState;
}
const store = createStore(reducer);
- currentState : 현재 스테이트
- action : 어떻게 바꿀 것인가에 대한 요청을 받는 action
4. 리덕스 4인방
- react-redux에서 제공해줌
- Provider : 컴포넌트로, state를 어떤 컴포넌트에 제공할 것인가에 대해 가장 바깥쪽의 울타리를 정하는데 사용
- 필요한 애들을 Provider로 감싸줌
- store를 정의하여 에러 방지
- useSelector : 어떤 state값을 쓸지 결정
function Left3(props) {
const number = useSelector((state) => state.number); //number라는 state값을 쓰겠다!
return (
<div>
<h1> Left3: {number} </h1>
</div>
)
}
- useDispatch : state값을 변경시킬 때 사용
- 이 state를 사용하고 있는 number만 바뀐다 -> parent들은 다시 렌더링 안되어 퍼포먼스에 상당한 도움을 받음
import { createStore } from 'redux';
function reducer(currentState, action){
if(currentState === undefined ) {
return {
number: 1, //number라는 state값의 기본이 1이다
}
}
const newState = {...currentState};
if(action.type === 'PLUS') { //action이 PLUS면 1을 더해주라
newState.number++;
}
return newState;
}
const store = createStore(reducer);
...
function Rright3(props){
const dispatch = useDispatch(); //dispatch 데려오기
return(
<div>
<h1>Right3</h1>
<input
type="button"
value="+"
onClick={()=> {
dispatch({type: 'PLUS'}); //클릭 시, PLUS라고 actin에 전해주기
})
></input>
</div>
);
}
- connect : 재사용성 할 때 사용
출처 : 생활코딩