Language: JavaScript
State Management
Redux was created by Dan Abramov and Andrew Clark in 2015. It was inspired by Flux but simplified the architecture, emphasizing a single immutable state tree and pure reducers. Redux became widely adopted for complex React applications to manage state consistently.
Redux is a predictable state container for JavaScript apps. It helps manage application state in a single store, enabling easier debugging, testing, and predictable behavior across the app.
npm install reduxyarn add redux<script src='https://unpkg.com/redux/dist/redux.min.js'></script>Download the Redux package from npm or the GitHub repository and include it in your project.Redux uses a single store to hold the entire state of the application. State changes are made via actions and handled by pure reducer functions. Middleware can extend Redux with additional capabilities like async actions.
import { createStore } from 'redux';
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
switch(action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
};
const store = createStore(reducer);
console.log(store.getState());Creates a Redux store with an initial state and a simple reducer that handles an INCREMENT action.
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState());Dispatches an action to update the state and prints the new state.
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const asyncAction = () => dispatch => {
setTimeout(() => {
dispatch({ type: 'INCREMENT' });
}, 1000);
};
const store = createStore(reducer, applyMiddleware(thunk));
store.dispatch(asyncAction());Adds asynchronous action handling using Redux Thunk middleware.
import { combineReducers, createStore } from 'redux';
const reducerA = (state = 0, action) => action.type === 'A' ? state + 1 : state;
const reducerB = (state = 0, action) => action.type === 'B' ? state + 1 : state;
const rootReducer = combineReducers({ a: reducerA, b: reducerB });
const store = createStore(rootReducer);Combines multiple reducers into a single root reducer for managing different parts of the state.
store.subscribe(() => console.log('State updated:', store.getState()));
store.dispatch({ type: 'INCREMENT' });Registers a listener to run whenever the state changes.
Keep state normalized and avoid nested structures when possible.
Use action creators to encapsulate action creation logic.
Keep reducers pure and free of side effects.
Use middleware for async actions instead of placing side effects in reducers.
Use Redux DevTools for debugging and inspecting state changes.