M. T. H. Titumir

M. T. H. Titumir

State Management with Redux in React

State Management with Redux in React

Explore how to manage application state effectively in React using Redux, a predictable state container for JavaScript apps.

Content

# State Management with Redux in React Redux is a predictable state container for JavaScript apps. It helps manage the state of your application in a single, centralized place. ## Core Concepts 1. **Store:** The single source of truth for your application's state. 2. **Actions:** Payloads of information that send data from your application to your store. 3. **Reducers:** Pure functions that take the current state and an action, and return the next state. ## Setting Up Redux with React First, install the necessary packages: ```bash npm install redux react-redux ``` Create a Redux store: ```javascript import { createStore } from 'redux'; import rootReducer from './reducers'; const store = createStore(rootReducer); ``` Wrap your React application with the `Provider` component: ```javascript import { Provider } from 'react-redux'; import store from './store'; function App() { return ( <Provider store={store}> <MyComponent /> </Provider> ); } ``` ## Example Here's a simple example of a counter using Redux: 1. **Actions:** ```javascript const increment = () => ({ type: 'INCREMENT' }); const decrement = () => ({ type: 'DECREMENT' }); ``` 2. **Reducer:** ```javascript const counter = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } }; ``` 3. **Store:** ```javascript import { createStore } from 'redux'; import counter from './reducers/counter'; const store = createStore(counter); ``` 4. **React Component:** ```javascript import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; function Counter() { const count = useSelector((state) => state); const dispatch = useDispatch(); return ( <div> <button onClick={() => dispatch(increment())}>+</button> <span>{count}</span> <button onClick={() => dispatch(decrement())}>-</button> </div> ); } ``` With this setup, you can manage the state of your application in a predictable and consistent way using Redux.

Long Description

Managing state in a React application can be challenging, especially as the app grows. Redux provides a predictable state container that helps manage application state in a consistent way. This blog covers the basics of Redux and how to integrate it with React.

Tags