To use Redux with React for state management, follow the steps below:
npm install redux react-redux
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;
}
}
createStore
method:import { createStore } from 'redux';
const store = createStore(reducer);
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')
);
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.