React-Redux

moono·2023년 7월 5일
0

React

목록 보기
12/12

props로 인한 무한드릴링이 사라지고,
해당 state를 사용한 컴포넌트만 사용되기 때문에
부모요소까지 다시 렌더링하지 않고, 해당 컴포넌트가 있는 부분만 렌더링하기때문에
퍼포먼스에도 상당한 도움을 받을 수 있고 react 의 생산성을 높일 수 있다.

먼저 redux, react-redux 깔기

$ npm i redux react-redux

react-redux의 4인방

  • Provider : state를 어떤 컴포넌트들에게 제공할 것인가에 대한 가장 밖의 울타리를 정의하는 것
    ⇒ 필요한 애들을 <Provider> 필요한 애들 </Provider> 이렇게 감싸주기
    ⇒ store를 반드시 정의해줘야 함
  • useSelector: 어떤 state 를 쓸건지 선택하는 것
    ⇒ 예를 들어 number의 값을 Left2에 노출시켜주고자 할 떄 사용
    ⇒ useSelector는 함수를 인자로 받는데, 이 함수는 state값을 입력값으로 받고 저 state 중에 어떤 값을 사용할지 지정해주기
  • useDispatch: state 값 변경할 때
    ⇒ dispatch 가져올 때 사용, action 전달
  • connect: 사용하기 어려움. 재사용성에서 꼭 필요한건데, 그게 아니면 필요 없음

Store, reducer 만들고 적용하기

import {createStore} from 'redux'
import {Provider, useSelector, useDispatch} from 'react-redux'

// store만들기 위해 반드시 만들어야 하는 것
function reducer(currentState, action) { // 현재 state 와 어떻게 바꿀지에 대한 action 의 2개 인자를 받음
//store 안에 있는 state를 어떻게 바꿀 것인가를 결정하는 것
  if(currentState === undefined) {
    // 만약 현재 state 가 undefined 라면 (state가 정의되지 않았다면)
    return {
      number: 1; // 기존의 state 값을 직접 넣기
    }
  }
  const newState = {...currentState} // 각각의 state를 불변하게 유지해야되기 때문에 state 복제하기
  if (action.type === "PLUS") {
    newState.number++
  }
  // return 한 값이 새로운 state
  return newState;
}

const store = createStore(reducer)

export default function App() {
  // const [number, setNumber] = useState(1); // store 만들었으니까 지우기
  return (
    <div>
      <h1>Root : </h1>
      <div>
        // Provider store에 만든 store 넣어주기
        <Provider store={store}> 
          // 아래에 있는 컴포넌트들은 이제 store를 사용할 수 있게 됨
          <Left1></Left1>
          <Right1></Right1>
        </Provider>
      </div>
    </div>
  )
}

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

function Left2(props) {
  //function num(state) {
  //  return state.number;
  //}
  //const number = useSelector(num)
  const number = useSelector((state) => state.number)
  return (
    <div>
      <h1>Left2: {number}</h1>
    </div>
  )
}

function Right1(props) {
  return (
    <div>
      <h1>Right1</h1>
      <Right2></Right2>
    </div>
  )
}

function Right2(props) {
  const dispatch = useDispatch();
  return (
    <div>
      <h1>Right2</h1>
      <input type="button" value="+" onClick={()=>{
          dispatch({type: "PLUS"}) // PLUS 라는 action 전달, 그러면 reducer 호출
        }}>
      </input>
    </div>
  )
}


참고링크

0개의 댓글