Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

ENN

Redux, react-redux, redux toolkit 본문

프론트엔드

Redux, react-redux, redux toolkit

asaei623 2022. 9. 13. 00:51

Redux

#Redux의 동작 구조

  • store : 정보가 저장되는 곳
    • state : 실제 정보가 저장되는 곳. 직접적인 접근이 불가능하다.
    • reducer : 현재 state값과 action을 인자로 받아서 새로운 state를 리턴하는 가공자이다.
    • dispatch : reducer를 호출해서 state값을 변경한 뒤, subscribe을 이용해 render한다.
    • subscribe : render함수를 등록해놓으면 state가 바뀔 때마다 render함수가 실행된다.
    • getState
  • render : getState를 통해 state를 가져와 ui를 만든다.
  • action : dispatch에게 전달된다.

#Redux를 쓰면 좋은 이유

  • 중앙집중적 데이터 관리
    • 하나의 부품이 변경되었을 때, 중앙의 redux가 나머지 부품들에게 변경되었다는 사실을 알리면 각 부품이 알아서 리렌더된다.
    • 따라서 부품 간의 상호작용이 간단해졌다.
  • state가 변화된 과정을 모두 기록한다.
    • 쉽게 이전 상태로 돌아갈 수 있다. 즉 버전관리가 된다.

React-redux

  • redux를 react에서 쉽게 사용할 수 있도록 돕는 도구

#import

  • npm install redux react-redux
  • import {createStrore} from ‘redux’;
  • import {Provider, useSelector, useDispatch, connect} from ‘react-redux’;

#Provider

  • 원하는 부분을 Provider 태그로 감싸면 store의 state를 사용할 수 있게 된다.
  • store을 Provider에게 prop으로 넘겨줘야 한다.

#useDispatch

  • dispatch 사용법과 동일하다.

Redux toolkit

  • redux 개발환경 구축을 쉽게 만들어주는 도구

#설치

  • npm create-react-app my-app —template redux
    • 리액트 앱 시작시 —template redux만 추가하면 자동으로 redux toolkit이 설치된다.
  • 또는 npm install @reduxjs/toolkit

#Slice

  • import {createSlice} from ‘@reduxjs/toolkit’;
  • 하나의 store로 관리하기 불편할때, 작은 slice들로 나누어 관리할 수 있다.

#configureStore

  • import {configureStore} from ‘@reduxjs/toolkit’;
  • 여러 slice를 모아 하나의 store로 만들어 준다.

출처 : 생활코딩

'프론트엔드' 카테고리의 다른 글

Styled-components  (0) 2022.09.14
Next.js  (0) 2022.09.14
리액트 훅(useState, useEffect, useMemo, useCallback, useRef,  (0) 2022.09.13
[React] 리액트 Router  (0) 2022.09.11
npx vs npm vs yarn  (0) 2022.09.10