각 클래스 컴포넌트에 connect( ) 함수를 사용하여 저장소를 연결하고 전역 상태 및 디스패치 메서드를 wrapping
하는 형태가 함수형 컴포넌트에서 사용 할 때 가독성이나 api 호출하는 부분이 불편했습니다.
Hooks for React-Redux:
Redux hook API는 connect()를 대신해서 useSelector, useDispatch, useStore과 같은 훅스를 사용할 수 있습니다.
- useSelector(): useSelector hook is a replacement of the mapStateToProps. It runs whenever function component renders. Its purpose is to extract data from the Redux store state.
- useDispatch(): It acts as a replacement for mapDispatchToProps. It returns to the reference to the dispatch object.
- useStore(): This returns the reference of the Redux store that was wrapped in the <provider>. It is not recommended for frequent use but can be used in scenarios like replacing reducers.참고: blog.bitsrc.io/using-react-redux-hooks-97654aff01e4
How to Use Redux with React Hooks
How to use hooks to connect your functional components to your app’s Redux store
blog.bitsrc.io
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from "./vehicle.js";
import App from "./app";
const vehicle = createStore(reducer);
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={vehicle}>
<App />
</Provider>,
rootElement
);
useSelector()는 Redux store state을 리턴한다.
useDispatch는 “mapDispatchToProps”과 비슷하게 작용한다.
버튼을 클릭하면 액션은 디스패치된다.
import React from "react";
import { useSelector } from "react-redux";
import { useDispatch } from "react-redux";
function App() {
const counter = useSelector(state => state);
const dispatch = useDispatch();
return (
<div className="App">
<button
onClick={() =>
dispatch({
type: "Car"
})
}
>
Car
</button>
<h1>{counter.vehicle}</h1>
<button
onClick={() =>
dispatch({
type: "Bike"
})
}
>
Bike
</button>
</div>
);
}
export default App;
'리덕스' 카테고리의 다른 글
Async Actions with Redux Thunk (0) | 2021.05.03 |
---|