React-redux_생활코딩

Juyeon.it·2022년 6월 19일
0

구현하려고 하는 것

  • Right3 아래에 있는 +버튼을 누르면 Root, Left1,2,3에 있는 숫자가 하나씩 늘어나도록 만들기
    Without redux

redux 없이 구현

  • prop에 onIncrease를 넣어 위로 쭉 올려서 구현함
  • 박스가 1000개라고 해보면 너무 번거로운 일이 됨

redux를 이용하여 구현

  • redux는 독립적인 도구!
    - react라는 독립적인 도구와 redux라는 독립적인 도구를 연결하는 도구가 react redux임
    - npm install redux react-redux

  • react-redux 3대장
    - Provider: state들을 어떤 컴포넌트에 제공할 것인가. 울타리처럼 감쌀 때 씀, props으로 반드시 store를 가지고 있어야 함
    - useSelector: state를 무선으로 연결할 때 사용. 함수를 인자로 받음
    - useDispatch

  • 장점!!!
    - + 버튼을 클릭해서 Left3에 있는 값이 바뀔 때, number라는 state를 사용하고 있는 Left3만 다시 랜더링 되고 이것의 부모 요소들(Left2, Left1 등)을 다시 랜더링하지 않음 -> 퍼포먼스에 좋음

import React, { useState } from 'react';
import './style.css';
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch, connect } from 'react-redux';

// 스토어 생성시 반드시 필요한 것
// 스토어 안에 있는 state를 어떻게 바꿀 것인가를 결정함
// parameter로 현재 상태인 currentState와 어떻게 바꿀 것인가 하는 action을 받음
function reducer(currentState, action) {
  if (currentState === undefined) {
    // 기본 상태 설정
    return {
      number: 1,
    };
  }
  // 과거의 값을 복제하여 복제된 값을 수정하면 불변성 유지 가능
  const newState = { ...currentState };
  // useDispatch 관련
  if (action.type === 'PLUS') {
    newState.number++;
  }
  // 새로운 값 리턴
  return newState;
}

// 수정하면 안되니까 상수로 선언
// 스토어 생성
const store = createStore(reducer);

export default function App() {
  return (
    <div id="container">
      <h1>Root</h1>
      <div id="grid">
        <Provider store={store}>
          <Left1></Left1>
          <Right1></Right1>
        </Provider>
      </div>
    </div>
  );
}
function Left1(props) {
  return (
    <div>
      <h1>Left1 </h1>
      <Left2></Left2>
    </div>
  );
}
function Left2(props) {
  console.log('2');
  return (
    <div>
      <h1>Left2 : </h1>
      <Left3></Left3>
    </div>
  );
}
function Left3(props) {
  console.log('3');
  // store에 저장되어 있는 number state와 Left3의 number를 무선으로 연결
  const number = useSelector((state) => state.number);
  return (
    <div>
      <h1>Left3 : {number}</h1>
    </div>
  );
}
function Right1(props) {
  return (
    <div>
      <h1>Right1</h1>
      <Right2></Right2>
    </div>
  );
}
function Right2(props) {
  return (
    <div>
      <h1>Right2</h1>
      <Right3></Right3>
    </div>
  );
}
function Right3(props) {
  const dispatch = useDispatch();
  return (
    <div>
      <h1>Right3</h1>
      <input
        type="button"
        value="+"
        onClick={() => {
          // reducer가 호출됨
          dispatch({ type: 'PLUS' });
        }}
      ></input>
    </div>
  );
}

참고자료

react-redux (2022년 개정판) by 생활코딩

0개의 댓글