Monday, January 1, 2024
How to create a React application using Redux hooks? Example Tutorial
Hello guys, Redux is one of the most popular state management library. It is often used with React apps that are huge in size and state are shared among multiple components. Redux is a complex library to understand and even more complex to implement. It was even more complex and complicated before the introduction of react-redux hooks. Earlier, the connect method provided by Redux was used to connect React with the Redux store. Using connect method with other methods such as mapstatetoprops was complicated. But with the introduction of react-redux hooks, it is easy to use redux with redux. In this article, we will discuss what are react-redux hooks and how to use them with React.
1. useSelector()
2. useDispatch()
3. useStore()
In other world, there are two react-redux hooks - useDisptach and useSelector.
The useDispatch hook returns a reference to the dispatch method from the store. The reference is stored in a variable and then, actions are dispatched using it.
The useSelector hook takes the current state as an argument and returns the global state or part of it.
Now, let’s understand how to use both of these hooks with react with the help of an example.
First install, redux, and react-redux using the following commands.
npminstallredux
npminstallreact-redux
First, we need to create a store. Create a new file in the “src“ folder and name it “store.js”. Add the following code to it.
import { createStore } from"redux";
conststore = createStore()
exportdefaultstore;
Next, open the “index.js” file and wrap the App component in the Provider. The store we created earlier must be provided as the value of the “store” attribute.
importReactfrom"react";
importReactDOMfrom"react-dom";
import { Provider } from"react-redux";
importAppfrom"./App";
importreportWebVitalsfrom"./reportWebVitals";
importstorefrom"./store";
ReactDOM.rendr(
<Providerstore={store}>
<App/>
</Provider>,
document.getElementById("root")
);
reportWebVitals();
We will create three components and these three components will share the global state among them.
Component1:
importReactfrom"react";
constComponent1 = () => {
constincrementHandler = () => {};
constdecrementHandler = () => {};
return (
<div>
<buttononClick={incrementHandler}>Increment</button>
<buttononClick={decrementHandler}>Decrement</button>
<hr/>
</div>
);
};
exportdefaultComponent1;
Two buttons are defined in the “Component1” - one for incrementing value and the other for decrementing.
Component2:
importReactfrom"react";
constComponent2 = () => {
return (
<div>
<h2>
{}
</h2>
</div>
);
};
exportdefaultComponent2;
“Component2” will display the state.
Component3:
importReactfrom"react";
constComponent3 = () => {
constcolorHandler = () => {
letcolor;
returncolor;
};
return (
<divstyle={{ backgroundColor:colorHandler(), padding:"20px" }}></div>
);
};
exportdefaultComponent3;
In “Component3”, “count” will be used to determine the color of the div.
We will create two actions - one to increment the value of “count” and the other to decrement it.
Create a new folder in “src” and name it “Actions”. In this folder, create a new file “actionCreators.js”. Add the following code to it.
exportconstincrementAction = (count) => {
return {
type:"INCREMENT",
payload:count,
};
};
exportconstdecrementAction = (count) => {
return {
type:"DECREMENT",
payload:count,
};
};
Next, create a new folder “Reducers” and add a new file “reducer.js” to it with the following code.
exportconstreducer = (state = { count:0 }, action) => {
switch (action.type) {
case"INCREMENT":
return {
...state,
count:action.payload + 1,
};
case"DECREMENT":
return {
...state,
count:action.payload - 1,
};
default:
return { ...state };
}
};
The reducer receives the state and action as parameters. Then, according to the “type” of action, the new state is returned. The “payload” is used to make changes in the “count”.
Let’s make some changes to the store.
import { createStore } from"redux";
import { reducer } from"./Reducers/reducers";
constinitialState = {
count:0,
};
conststore = createStore(reducer, initialState);
exportdefaultstore;
An initial state is added to the store. Now we can use react-redux hooks.
Let’s use the useSelector hook to fetch the global state in “Component2”.
importReactfrom"react";
import { useSelector } from"react-redux";
constComponent2 = () => {
const { count } = useSelector((state) =>state);
return (
<div>
<h2>{count}</h2>
<hr/>
</div>
);
};
exportdefaultComponent2;
In the above component, “count” is extracted from the global state using the useSelector hook.
Similarly, we can use the useSelector hook to extract “count” from the global state in “Component3”
importReactfrom"react";
import { useSelector } from"react-redux";
constComponent3 = () => {
const { count } = useSelector((state) =>state);
constcolorHandler = () => {
letcolor = count > 0 ? "green" : count < 0 ? "red" : "grey";
returncolor;
};
return (
<divstyle={{ backgroundColor:colorHandler(), padding:"20px" }}></div>
);
};
exportdefaultComponent3;
The “count” is used in the “colorHandler” to determine the color of the div.
Now, let’s use the useSelector hook as well as the useDispatch hook in the “Component1”.
importReactfrom"react";
import { useSelector, useDispatch } from"react-redux";
import {
decrementAction,
incrementAction,
} from"../ActionCreators/actionCreators";
constComponent1 = () => {
constdispatch = useDispatch();
const { count } = useSelector((state) =>state);
constincrementHandler = () => {
dispatch(incrementAction(count));
};
constdecrementHandler = () => {
dispatch(decrementAction(count));
};
return (
<div>
<buttononClick={incrementHandler}>Increment</button>
<buttononClick={decrementHandler}>Decrement</button>
<hr/>
</div>
);
};
exportdefaultComponent1;
In the “Component1”, first, the reference from the useDispatch hook is stored in a variable and then, the dispatch is used inside the “incrementHandler” and “decrementHandler” to dispatch the actions. We need the “count” because it should be passed to the actions creators and for this, we used the useSelector hook.
Everything is ready. Let’s check the output.
Yes, the value of “count” is changing on button clicks. Because of the change in the “count”, the color div is also changing.
Wrapping it up
Understanding react-redux hooks can take some time and practice but once you understand the concept of these hooks, working with redux will be very easy. In this tutorial, we discussed what are useDispatch and useSelector hooks and how to use them to manage the global state in redux.
Other React and Web development Articles and resources you may like
- The Frontend and Backend Developer RoadMap
- 5 Courses to Learn Ruby and Rails for Free
- 10 Books and Courses to learn Angular
- My favorite free Courses to learn Angular and React
- My favorite books to learn React.js
- 5 Best courses to learn React Native
- 5 Courses to learn Object-Oriented Programming for Free
- 5 Free Courses to learn Kubernetes
- 10 Courses to learn AWS for beginners
- 5 Free Docker Courses for Java and DevOps Engineer
- 5 Online training courses to learn Angular for Free
- 3 Books and Courses to Learn RESTful Web Services in Java
Thanks for reading this article so far. If you like this React tutorial and examples of useEfect hooks, then please share them with your friends and colleagues. If you have any questions or feedback, then please drop a comment.

1 comment :
What are the pros and cons of using hooks in React.js?
Post a Comment