본문 바로가기
부트캠프교육중/react

Redux Hook

by 뭉지야 2023. 2. 24.
728x90

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

 

<useDispatch()>
-dispatch함수를 반환.
-action 객체를 reducer로 전달해주는 dispatch함수를 반환하는 메서드이다.

import { useDispatch } from 'react-redux'

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

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



<useSelector()>
-컴포넌트와 state를 연결하여 redux의 state에 접근할수있게 해주는 메서드.
-redux hooks 메서드는 'redux'가 아니라 'react-redux'에서 불러온다.

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

<Redux의 세가지 원칙>
1. Single source of truth
동일한 데이터는 항상 같은 곳에서 가지고 와야 한다는 의미이다.
redux에는 데이터를 저장하는 store라는 단 하나뿐인 공간이 있음과 연결이 되는 원칙이다.

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

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


//index.js

import { Provider } from 'react-redux';
import { createStore } from 'redux';

const 체중 = 100;

function reducer(state = 체중, action){
if(action.type === '증가'){
state++;
return state
}  else if (action.type === '감소'){
state--;
return state
} else {
return state
}
}
let store = createStore(reducer)

ReactDOM.render(
<React.StrictMode>
<Provider store = {store}>
<App />
</Provider>
</React.StrictMode>
document.getElementById('root')
)
//App.js

import './App.css';
import { useDispatch, useSelector } from 'react-redux'

function App() {
const 꺼내온거 = useSelector((state)=> state);
const dispatch = useDispatch()

return (
<div className="App">
<p>님의 처참한 몸무게 : {꺼내온거}</p>
<button onClick={()=> {dispatch({type: '증가'}) }}>더하기</button>
</div>
);
}

export default App;
728x90

'부트캠프교육중 > react' 카테고리의 다른 글

빌드와 번들링 정리  (0) 2023.03.20
Redux 간단히 정리  (0) 2023.02.27
Redux 2  (0) 2023.02.24
Redux 1  (0) 2023.02.24
useRef  (1) 2023.02.23