Redux is a predictable state container for JavaScript apps based on the unidirectional data flow pattern.
Core Concepts & Store Creation
import { createStore } from 'redux';
// Reducer function: pure function calculating next state
function counterReducer(state = { value: 0 }, action) {
switch (action.type) {
case 'counter/incremented':
return { value: state.value + 1 };
case 'counter/decremented':
return { value: state.value - 1 };
default:
return state;
}
}
// Create store
const store = createStore(counterReducer);
// Subscribe to state changes
const unsubscribe = store.subscribe(() => {
console.log('Current state:', store.getState());
});
// Dispatch actions
store.dispatch({ type: 'counter/incremented' }); // { value: 1 }
store.dispatch({ type: 'counter/decremented' }); // { value: 0 }
Action Creators & Middleware
// Action Creator
const incrementBy = (amount) => ({
type: 'counter/incrementBy',
payload: amount
});
// Middleware pattern (logging, async thunks)
const loggerMiddleware = (storeAPI) => (next) => (action) => {
console.log('Dispatching:', action);
const result = next(action);
console.log('Next state:', storeAPI.getState());
return result;
};
React Redux Hooks (useSelector & useDispatch)
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
export function Counter() {
const count = useSelector((state) => state.value);
const dispatch = useDispatch();
return (
<div>
<span>Count: {count}</span>
<button onClick={() => dispatch({ type: 'counter/incremented' })}>
+
</button>
</div>
);
}
Modern Redux Toolkit (RTK)
Modern Redux applications use Redux Toolkit (createSlice, configureStore):
import { createSlice, configureStore } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; },
decrement: (state) => { state.value -= 1; }
}
});
export const { increment, decrement } = counterSlice.actions;
export const store = configureStore({ reducer: counterSlice.reducer });