Here is how to use Redux with Hooks in 3 simple steps : Counter example.
Source code: https://github.com/trackmystories/Redux-hooks-counter-app-with-axios.
NOTE: https://react-redux.js.org/introduction/getting-started
Step 1:
create a reducer.js file, define and combine your reducers:
reducer.js
import { combineReducers } from "redux";
const counter = (state = 0, action) => {
switch (action.type) {
case "ADD":
return state + 1;
case "SUBTRACT":
return state - 1;
default:
return state;
}
};
const rootReducer = combineReducers({
counter
// additional reducers ...
});
export default rootReducer;
Step 2
Create a counter component which will access the state and render it to the view:
NOTE: please refer to "Redux Terms and Concepts" to get a better understanding of Actions, State and View.
https://redux.js.org/tutorials/essentials/part-1-overview-concepts
You don't need to use connect mapStateToProps and dispatchStateToProps with redux hooks instead use { useDispatch, useSelector }.
We can pass the actions "ADD" and "SUBTRACT" inside of the button directly, without defining an action.js file.
CounterComponent.js
import React from "react";
import { useDispatch, useSelector } from "react-redux";
export default function CounterComponent() {
const dispatch = useDispatch(); // dispatct action "ADD","SUBTRACT".
const counter = useSelector((state) => state.counter); // your apps state.
return (
<div>
// dispatch "SUBTRACT"
<button onClick={() => dispatch({ type: "SUBTRACT",})}>
SUBTRACT
<button>
// pass the current state
<text> display count : {counter}</text>
// dispatch "ADD"
<button onClick={() => dispatch({ type: "ADD",})}>
ADD
<button>
</div>
)
}
Step 3:
Lastly link your RootReducer to the createStore and pass it to the Provider.
App.js
import React from 'react';
import { Provider } from "react-redux";
import { createStore } from "redux";
import CounterComponent from './CounterComponent.jsx';
// import your reducers
import rootReducer from "./reducers";
// link your reducers to the store
const store = createStore(rootReducer);
// Pass your store to the Provider wrapping your Component.
export default function App() {
return (
<>
<Provider store={store}>
<CounterComponent/>
</Provider>
</>
);
};
redux-react-hookis a good package... you can read the entire source in a few minutes