React

React Hooks

mellomello.made 2022. 7. 8. 00:25

Redux의 세 가지 원칙

 

1. Single source of truth

동일한 데이터는 항상 같은 곳에서 가지고 와야 한다는 의미.

즉, Redux에는 데이터를 저장하는 Store라는 단 하나뿐인 공간이 있음과 연결이 되는 원칙.

2. State is read-only

상태는 읽기 전용이라는 뜻으로, React에서 상태갱신함수로만 상태를 변경할 수 있었던 것처럼, Redux의 상태도 직접 변경할 수 없음을 의미. 즉, Action 객체가 있어야만 상태를 변경할 수 있음과 연결되는 원칙.

3. Changes are made with pure functions

변경은 순수함수로만 가능하다는 뜻으로, 상태가 엉뚱한 값으로 변경되는 일이 없도록 순수함수로 작성되어야하는 Reducer와 연결되는 원칙.


Store

Store는 상태가 관리되는 오직 하나뿐인 저장소의 역할을 한다. Redux 앱의 state가 저장되어 있는 공간이다. 

import { createStore } from 'redux';

const store = createStore(rootReducer);

createStore 메서드를 활용해 Reducer를 연결해서 Store를 생성할 수 있다.

 

 

 

Redux Hooks

Action, Reducer, Dispatch, Store 개념들을 연결시켜주는 Redux Hooks.

Redux Hooks는 React에서 Redux를 사용할 때 활용할 수 있는 Hooks 메서드를 제공한다.

그 중에서 크게 useSelector(), useDispatch() 이 두 가지의 메서드를 기억하면 됨.

useSelector()

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


// Redux Hooks 메서드는 'redux'가 아니라 'react-redux'에서 불러옵니다.
import { useSelector } from 'react-redux'
const counter = useSelector(state => state.counterReducer)
console.log(counter) // 1

useDispatch()

useDispatch() 는 Action 객체를 Reducer로 전달해 주는 메서드. dispatch 함수도 useDispatch()를 사용한 것이다.


import { useDispatch } from 'react-redux'

const dispatch = useDispatch()
dispatch( increase() )
console.log(counter) // 2

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

 

참조 사이트

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

https://redux.js.org/

'React' 카테고리의 다른 글

웹팩의 핵심 컨셉  (0) 2022.07.27
번들링과 웹팩  (0) 2022.07.26
React 상태관리  (0) 2022.07.07
Cmarket (Hooks 버전)/ useEffect  (0) 2022.07.06
[React] CDD 개발 도구 Styled Components Props 활용  (0) 2022.07.01