Redux
Redux is a state management library for JavaScript applications, particularly those built with React. It provides a predictable way to manage application state and helps you write applications that are simple, scalable, and maintainable.
Redux Principles
Redux follows three core principles:
Single Source of Truth: The state of your whole application is stored in a single JavaScript object called the store. This makes it easy to access and manage the application state from anywhere in your React components.
State is Read-Only: The state object is read-only, which means it cannot be modified directly. Instead, you use actions to describe what changes should be made to the state. Actions are plain JavaScript objects that have a
type
property which describes the type of action being performed.Changes are Made with Pure Functions: To update the state, you write reducers, which are pure functions that take the current state and an action as input, and return a new state. The state is not mutated directly, but instead, a new state object is created.
Example
Here's an example of how you can use Redux to manage a counter in a React application:
1// Reducer
2const initialState = {
3 counter: 0
4};
5
6const counterReducer = (state = initialState, action) => {
7 switch (action.type) {
8 case 'INCREMENT':
9 return {
10 ...state,
11 counter: state.counter + 1
12 };
13 case 'DECREMENT':
14 return {
15 ...state,
16 counter: state.counter - 1
17 };
18 default:
19 return state;
20 }
21};
22
23// Store
24const store = Redux.createStore(counterReducer);
25
26// Initial state
27console.log(store.getState()); // { counter: 0 }
28
29// Dispatch an action
30store.dispatch({ type: 'INCREMENT' });
31
32// New state
33console.log(store.getState()); // { counter: 1 }
xxxxxxxxxx
const initialState = {
counter: 0
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return {
state,
counter: state.counter + 1
};
case 'DECREMENT':
return {
state,
counter: state.counter - 1
};
default:
return state;
}
};
const store = Redux.createStore(counterReducer);
console.log(store.getState());
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState());