This example will demonstrate how to set up Redux for state management in a React application to create a counter Simply .
Requirements
: You must have knowledge of react js
step1
make sure you have Redux installed in your project. You can install it using npm or yarn:
npm install redux react-redux
Here's a step-by-step example:
- Create Redux Actions and Reducer
I know very well that everyone who explained this example before was dividing it into three files
Action.js & Reducer.js & Store.js
But here I will put them in one file just for simplicity and so that you do not get dizzy
its just redux not NASA
Create a file for your Redux actions and reducers. Let's call it counter.js
. Define your actions and a reducer function.
// counter.js
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
// Action creators
export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
// Reducer
const initialState = { count: 0 };
export default function counterReducer(state = initialState, action) {
switch (action.type) {
case INCREMENT:
return { count: state.count + 1 };
case DECREMENT:
return { count: state.count - 1 };
default:
return state;
}
}
- Configure Redux Store
In your main application file, configure the Redux store and connect it to your React app using the Provider
component.
// index.js or App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import counterReducer from './counter';
import App from './App';
const store = createStore(counterReducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
- Create the React Component
Now, create a React component that will display the counter and handle the actions.
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './counter';
function App() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<h1>Redux Counter</h1>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
}
export default App;
- Run the Application
Start your React application using npm start
or your preferred method.
This example demonstrates a simple Redux counter in a React application. When you click the "Increment" or "Decrement" buttons, the Redux store will manage the state, and the UI will update accordingly.
Top comments (0)