react-redux 간단한 사용법 예제

아래는 react-redux 개념을 익히기 위한 간단한 예제입니다. 생활코딩(https://www.youtube.com/watch?v=yjuwpf7VH74) 유튜브 강좌에서 설명한 코드로 종종 참고할 목적으로 기록합니다.

코드를 간단히 설명하면 좌측 컴포넌트는 Left1, Left2, Left3으로의 하위 컴포넌트들을 그리는 구조로 되어 있고 우측 컴포넌트는 마찬가지로 Right1, Right2, Right3으로의 하위 컴포넌트들로 구성되어 있습니다. 예제에서는 props 전달 없이 어떻게 react-redux를 이용해서 하위 컴포넌트가 정보를 표시하고 다른 컴포넌트에서 값을 변경할 수 있는지를 보여줍니다.

App.js 파일

import React, { useState } from 'react';
import './App.css';
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } 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] = useState(1);

  return (
    <div id="container">
      <h1>Root</h1>
      <div id="grid">
        <Provider store={ store }>
          <Left1 number={number}></Left1>
          <Right1 onIncrease={() => { setNumber(number + 1); }}></Right1>
        </Provider>
      </div>
    </div>
  );
}

function Left1(props) {
  return (
    <div>
      <h1>Left1 : </h1>
      <Left2></Left2>
    </div>
  );
}

function Left2(props) {
  return (
    <div>
      <h1>Left2 : </h1>
      <Left3></Left3>
    </div>
  );
}

function Left3(props) {
  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={() => { 
        dispatch({type: 'PLUS'});
       }}></input>
    </div>
  );
}

Leave a Reply