How to use React-Redux Hooks In ReactJS
React-Redux provides hooks like useSelector
and useDispatch
for functional components. useSelector
enables components to select data from the Redux store state. useDispatch
allows components to dispatch actions to update the Redux store. Hooks streamline state management in functional components, reducing reliance on higher-order components. They offer a more modern and concise way to interact with Redux within functional components. Developers can leverage React’s hooks API to integrate Redux seamlessly into their functional component workflows
Install the required modules and dependencies.
npm i react react-dom @reduxjs/toolkit react-redux
Example: Below is an example of using React-Redux Hooks
// Counter.js
import React from "react";
import {
useSelector,
useDispatch
} from 'react-redux'
import './style.css'
import {
increment,
decrement
} from "./store";
export default function Counter() {
const count = useSelector((state) => state.count)
const dispatch = useDispatch()
return (
<div>
<div id='head_comp'>
<h2 id='counter_head'>Counter</h2>
<img src="https://media.w3wiki.org/gfg-gg-logo.svg"
alt="gfg_logo" />
</div>
<div id='comp_1' >
<div id='comp_2' >
<button
onClick={() => dispatch(decrement())}
id='negative_btn'>-
</button>
<span id='count_value' >{count}</span>
<button
onClick={() => dispatch(increment())}
id='positive_btn' >+
</button>
</div>
</div>
</div>
);
};
// store.js
import { configureStore } from "@reduxjs/toolkit";
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
count: 0
}
const countSlice = createSlice({
name: 'Count Slice',
initialState,
reducers: {
increment: (state, action) => {
state.count = state.count + 1;
},
decrement: (state, action) => {
state.count = state.count - 1;
},
}
})
export default configureStore({
reducer: countSlice.reducer
})
export const { increment, decrement } = countSlice.actions
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>,
document.getElementById('root')
);
Output:
Benefits of using React-Redux over plain Redux
React-Redux streamlines state management in React applications by integrating seamlessly with Redux, eliminating prop drilling. It enhances predictability and scalability through centralized state management and facilitates the creation of reusable UI components. This integration optimizes syntax, approaches, and implementation steps, offering a robust solution for building dynamic web applications.
We will discuss two approaches of React Redux over plain Redux and their benefits:
Table of Content
- Benefits of using React-Redux over plain Redux
- Using Higher-Order Components (HOCs)
- Using React-Redux Hooks:
Contact Us