What is the recommended approach to centralize state handling across multiple React components using Redux

0 votes
Can you tell me What is the recommended approach to centralize state handling across multiple React components using Redux?
Mar 11 in Node-js by Ashutosh
• 23,230 points
60 views

1 answer to this question.

0 votes

The recommended approach to centralize state handling across multiple React components using Redux involves these steps:

1. Install Redux & React-Redux

npm install redux react-redux @reduxjs/toolkit

2. Create a Redux Slice (features/counterSlice.js)

import { createSlice } from '@reduxjs/toolkit';

const counterSlice = createSlice({

  name: 'counter',

  initialState: { value: 0 },

  reducers: {

    increment: (state) => { state.value += 1; },

    decrement: (state) => { state.value -= 1; }

  }

});

export const { increment, decrement } = counterSlice.actions;

export default counterSlice.reducer;

3. Setup Store (store.js)

import { configureStore } from '@reduxjs/toolkit';

import counterReducer from './features/counterSlice';

const store = configureStore({

  reducer: { counter: counterReducer }

});

export default store;

4. Provide Store in index.js

import React from 'react';

import ReactDOM from 'react-dom';

import { Provider } from 'react-redux';

import store from './store';

import App from './App';

ReactDOM.render(

  <Provider store={store}>

    <App />

  </Provider>,

  document.getElementById('root')

);

5. Use Redux State in Components (Counter.js)

import { useSelector, useDispatch } from 'react-redux';

import { increment, decrement } from '../features/counterSlice';

const Counter = () => {

  const count = useSelector((state) => state.counter.value);

  const dispatch = useDispatch();

  return (

    <div>

      <h1>{count}</h1>

      <button onClick={() => dispatch(increment())}>+</button>

      <button onClick={() => dispatch(decrement())}>-</button>

    </div>

  );

};

export default Counter;

answered Mar 11 by Tanmay

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer

What is the process to parse JSON using Node.js?

You can parse JSON data using the ...READ MORE

answered Feb 10 in Node-js by Navya
78 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

What is the difference between Node.js and Express.js?

Feature Node.js Express.js Definition A runtime environment for executing JavaScript outside ...READ MORE

answered Mar 11 in Node-js by Tanmay
55 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

What are the approaches to testing in React?

Testing in React ensures your components, logic, ...READ MORE

answered Dec 12, 2024 in Node-js by Navya
114 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP