Step by step implementation of implementing redux in reactjs
Here is a step-by-step guide on how to create a Redux store in ReactJS:
- Install the Redux and React Redux packages using npm or yarn.
// Using npm
npm install redux react-redux
// Using yarn
yarn add redux react-redux
- Create a new file called
store.js
and import thecreateStore
andapplyMiddleware
functions from the Redux package.
import { createStore, applyMiddleware } from 'redux';
- Define a reducer function that takes the current state of the application and an action, and returns the new state. The reducer function should handle all of the possible actions that can be performed in your application.
const reducer = (state, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, counter: state.counter + 1 };
case 'DECREMENT':
return { ...state, counter: state.counter - 1 };
default:
return state;
}
};
- Create the Redux store by calling the
createStore
function and passing in the reducer function and the initial state of the application.
const initialState = {
counter: 0,
};
const store = createStore(reducer, initialState);
- If you want to use middleware with your Redux store, you can call the
applyMiddleware
function and pass in the middleware you want to use, and then pass the result to thecreateStore
function.
const initialState = {
counter: 0,
};
const middleware = applyMiddleware(logger, thunk);
const store = createStore(reducer, initialState, middleware);
- Import the
Provider
component from the React Redux package and wrap your root React component with it. Pass the Redux store to theProvider
component as a prop.
import { Provider } from 'react-redux';
function App() {
return (
<Provider store={store}>
<MyRootComponent />
</Provider>
);
}
- In any of your React components, you can connect them to the Redux store using the
connect
function from the React Redux package. Theconnect
function takes two arguments: amapStateToProps
function that maps the state of the Redux store to the props of your component, and amapDispatchToProps
function that maps the dispatch function to the props of your component.
import { connect } from 'react-redux';
function MyComponent(props) {
return (
<div>
<p>Counter: {props.counter}</p>
<button onClick={props.increment}>Increment</button>
<button onClick={props.decrement}>Decrement</button>
</div>
);
}
const mapStateToProps = (state) => ({
counter: state.counter,
});
const mapDispatchToProps = (dispatch) => ({
increment: () => dispatch({ type: 'INCREMENT' }),
Comments
Post a Comment