Redux

이유정·2022년 11월 2일
1

코드스테이츠 TIL

목록 보기
41/62

store

import {Provider} from 'react-redux';  

// store을 손쉽게 사용할 수 있게 하는 컴포넌트 
import {legacy_createStore as createStore} from 'redux';

// redux 에서 createStore을 불러온다. 
<Provider store ={store}></Provider>

// 전역 상태 저장소 store을 사용하기 위해서는 App 컴포넌트를 Provider로 감싸줘야 한다
// props로 변수 store를 전달하자. 
const store = createStore(reducer)

// 변수 store에 createSotre 메서드를 통해 store를 만들어 주자. 
// 그리고 createStore에 인자로 Reducer 함수를 전달해야 한다. 

종합 코드 (index.js)

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { legacy_createStore as createStore } from 'redux';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

const reducer = () => {};

const store = createStore(reducer);

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

Reducer

  • 상태를 변경시키는 함수다.
  • Dispatch에게서 전달받은 Action 객체의 type 값에 따라 상태를 변경한다.
  • 순수함수이어야 한다. (외부 요인으로 인해 상태가 변경되면 안되기 때문에)
const count = 1
// Reducer 함수 생성할 땐 초기 상태를 인자로 요구한다. 
const counterReducer = (state = count, action) =>{
    // Action 객체의 type 값에 따라 분기하는 switch 조건문
    switch(action.type){
            // actiion === 'INCREASE'
        case 'INCREASE' : 
            return state +1
        case 'DECREASE' :
            return state -1
        case 'SET_NUMBER' :
            return action.payload
            // 해당 되는 경우가 없을 때 기존상태 그대로 리턴
        default:
            return state;
    }
}

이걸 아까 reducer 함수를 대신해 넣어보자

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { legacy_createStore as createStore } from 'redux';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

const count = 1;
const counterReducer = (state = count, action) => {
  switch (action.type) {
    case 'INCREASE':
      return state + 1;

    case 'DECREASE':
      return state - 1;

    case 'SET_NUMBER':
      return action.payload;

    default:
      return state;
  }
};

const store = createStore(counterReducer);

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

여러개의 Reducer를 사용할 때, combineReducers 메서드를 사용해서 하나의 Reducer로 합칠 수 있다.

import {combineReducers} from 'redux'; 
const rootReducer = combineReducers({
    counterReducer,
    anyReducer,
    ...
}); 

Action

: 어떤 액션을 취할 것인지 정의해 놓은 객체

  • type은 필수로 지정
  • only 대문자와 snake_case 로 작성해야 한다.
  • 필요에 따라 payload를 작성한다.
//payload가 필요 없는 경우 
{type: 'INCREASE'}
//payload가 필요한 경우 
{type: 'SET_NUMBER', payload: 5}

근데 위 예시처럼 보통 Action을 직접 작성하기보다는 Action 객체를 생성하는 함수를 만들어 사용하는 경우가 많다

// payload가 필요 없는 경우 
const increase = () => {
	return {
    	type: 'INCREASE'
    }
}
// payload가 필요한 경우 
const setNumber = (num) => {
	return {
    	type : 'SET_NUMBER',
      	payload : num
    }
}

위 Action Creator 함수를 총 종합 코드에 넣어보자.
만든 Action Creator 함수를 다른 파일에도 사용할 수 있게 export를 붙여야 한다.

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { legacy_createStore as createStore } from 'redux';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);


// 1
export const increase = () => {
  return {
    type: 'INCREASE'
  }
}
// 2
export const decrease = () =>{
  return {
    type: 'DECREASE'
  }
}


const count = 1;

const counterReducer = (state = count, action) => {
  
  switch (action.type) {
    
    case 'INCREASE':
      return state + 1;

    case 'DECREASE':
      return state - 1;

    case 'SET_NUMBER':
      return action.payload;

    default:
      return state;
  }
};

const store = createStore(counterReducer);

root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

알고가자 !

case

  • this_is_snake_case
  • ThisIsCamelCase
  • this-is-kebab-case

payload

  • 전송되는 데이터
  • 데이터 전송할 때 헤더, 메타데이터, 에러체크 비트 등의 요소들과 함께 보내는데, 이때 보내고자 하는 데이터 그 자체만을 의미하는 것이 페이로드이다.
  • 운송업에서 비롯된 말. 고객은 오직 20톤의 기름의 무게만 지급 pay 해라. 차체, 운전자의 무게는 낼 필요 없잖아? 따라서 pay-load

json으로 보는 실제 데이터에서 payload는 "data"dlek. 그 이외 데이터들은 전부 통신을 하는데 있어 부차적 정보다.

{
	"status" : 
	"from": "localhost",
	"to": "http://melonicedlatte.com/chatroom/1",
	"method": "GET",
	"data":{ "message" : "There is a cutty dog!" }
}

Dispatch

  • Reducer로 Action을 전달해주는 함수다.
  • Dispatch 전달인자로 Action의 객체가 전달된다.
  • Action 객체를 받은 Dispatch 함수는 Reducer를 호출한다.
// Action 객체를 직접 작성하는 경우
dispatch({type : 'INCREASE'});
dispatch({type : 'SET_NUMBER', payload:5});
// Action Creator를 사용하는 경우 
dispatch( increase());
dispatch( setNumber(5));

Redux Hooks

React-Redux 에서 Redux를 사용할 때 활용할 수 있는 Hooks 메서드를 제공한다.
1) useDispatch()
2) useSelector()

useDispatch

Action 객체를 Reducer로 전달해주는 Dispatch 함수를 반환하는 메서드
위에 Dispatch 설명할 때, dispatch 함수도 useDispatch()를 사용한 것.

import {useDispatch} from 'react-redux'

const dispatch = useDispatch()

dispatch(increase())
console.log(counter) // 2

dispatch(setNumber(5))
console.log(counter) // 5

나에게 주어진 미션! 읽으면서 정리를 해보았다.

작성되어 있던 index.js

이번 예제 App.js
왜 콘솔이 안될까? 이번 코드는 잘못 작성 했나보다. (//숫자 적혀있는 부분이 내가 작성한 코드 부분) 일단 pass !!!

useSelector

컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드다.

import {useSeletor} from 'react-redux'
const counter = useSelector(state => state)
console.log(counter) //1

ReadMe

App.js

index.js


Redux의 세가지 원칙

  1. Single source of truth
    : 동일한 데이터는 항상 같은 곳에서 가져와야 한다.
    : Redux에는 데이터를 저장하는 Store 라는 단 하나의 공간만 존재한다.

  2. State is read-only
    : 상태는 읽기 전용이다.
    : React에서 상태갱신함수로만 상태를 변경할 수 있었던 것처럼, Redux의 상태도 직접 변경할 수 없다
    : Action 객체가 있어야만 상태를 변경할 수 있다.

  3. Changes are mede with pure functions
    : 변경은 순수함수로만 가능하다.
    : 상태가 엉뚱한 값으로 변경되지 않게 순수함수로 작성되어야 하는 Reducer와 연결되는 원칙이다.

https://redux.js.org/
https://react-redux.js.org/

profile
팀에 기여하고, 개발자 생태계에 기여하는 엔지니어로

0개의 댓글