[React] react-redux의 useSlector() , useDispatch() Hooks

[React] react-redux의 useSlector() , useDispatch() Hooks

지금까지 connect( , )()를 사용해서 해야하는 줄 알았는데 알고보니 좋은 Hook이 있었다.

store에 접근할 때useSlector() , useDispatch() 를 이용해서 값을 받아오고 수정할 수 있다.

아래와 같이 store를 만들어 두었다고 하고 이 훅들을 이용해서 다음을 해보자

1.name을 받아오는 것

2.name의 값을 userA 에서 userB로 바꾸는 것

import { createStore } from 'redux'; const reducer = (state, action) => { if (state === undefined) { return { name: 'userA', }; } if (action.type === 'CHANGE') { return { ...state, name: action.name, }; } }; const store = createStore(reducer); export default store;

useSlector() 사용하기

import React from 'react'; import { useSelector } from 'react-redux'; const Example = () => { const name = useSelector((state) => state.name); return {name}; }; export default Example;

이렇게 사용하면 store의 오브젝트에서 name을 받아와 출력이 가능하다.

useDispatch() 사용하기

import React from 'react'; import { useDispatch } from 'react-redux'; const Example = (props) => { const dispatch = useDispatch(); const change = () => { dispatch({ type: 'CHANGE', name: 'userB' }); }; return {name}; }; export default Example;

간단하게 dispatch를 할 수 있다. dispatch를 hook으로 할당해주고 오브젝트를 보내서 store의 reducer에서 처리한다.

from http://jrepository.tistory.com/39 by ccl(A) rewrite - 2022-01-01 02:01:41