How to use Redux with React for state management?

To use Redux with React for state management, follow the steps below:

  1. Install Redux and React-Redux packages by running the following command in your terminal:
npm install redux react-redux
  1. Create a Redux store by defining the initial state and a reducer function. Here is an example of a simple reducer function:
const initialState = { count: 0 }; function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return {...state, count: state.count + 1}; case 'DECREMENT': return {...state, count: state.count - 1}; default: return state; } }
  1. Create a Redux store by passing the reducer function to the createStore method:
import { createStore } from 'redux'; const store = createStore(reducer);
  1. Wrap your root component with the Provider component from React-Redux and pass the Redux store as a prop:
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') );
  1. Connect your components to the Redux store using the connect function from React-Redux. Here is an example of connecting a component to the store:
import React from 'react'; import { connect } from 'react-redux'; const Counter = ({ count, dispatch }) => { return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button> </div> ); }; const mapStateToProps = (state) => ({ count: state.count }); export default connect(mapStateToProps)(Counter);

Now you have successfully integrated Redux with React for state management. You can dispatch actions to update the state in your Redux store, and the connected components will automatically re-render with the updated state.