Using Redux, you can manage and access all the application state from one centralized store. As Redux streams data unidirectionally, state changes are triggered by dispatching actions, and reducers update the state based on these actions. Whenever the state changes, components can receive updates from the store.
The following code snippet shows how to build a simple counter app using Redux:
import { createStore } from 'redux';
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const increment = () => ({
type: INCREMENT,
});
const decrement = () => ({
type: DECREMENT,
});
const counterReducer = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
const store = createStore(counterReducer);
store.dispatch(increment());
store.dispatch(increment());
store.dispatch(decrement());
const currentState = store.getState();
console.log(currentState); // Output: 1
To begin, we import the necessary library, which is Reduxs createStore. The next step is to define two action types: INCREMENT and DECREMENT. The counter state can be modified using these action types.
In this section, we create two action creators: increments and decrements. The functions return action objects with the type of action they are associated with.
Next, a reducer function (counterReducer) is defined to handle state changes based on dispatched actions. Reducers return the new state based on the current state and the action.
Redux stores are created by passing reducer functions into createStore.
Afterwards, we dispatch the actions using the stores dispatch method. Our example increments the counter twice then decrements it.
Last, the current state of the store is retrieved using getState and stored in the currentState variable. The current state is logged to the console, which in this case will be 1.