Managing State with Redux
Redux provides a centralized way to manage the state of your application. It allows you to store all the data that your application needs in a single place, called the store.
To manage the state with Redux, you need to define actions and reducers. Actions describe the changes that can occur in your application's state, while reducers specify how the state should be updated in response to those actions.
Here's an example of creating a simple counter application using Redux:
JAVASCRIPT
1// Let's create a simple counter application
2
3// Action types
4const INCREMENT = 'INCREMENT';
5const DECREMENT = 'DECREMENT';
6
7// Action creators
8function increment() {
9 return {
10 type: INCREMENT
11 };
12}
13
14function decrement() {
15 return {
16 type: DECREMENT
17 };
18}
19
20// Reducer
21function counterReducer(state = 0, action) {
22 switch (action.type) {
23 case INCREMENT:
24 return state + 1;
25 case DECREMENT:
26 return state - 1;
27 default:
28 return state;
29 }
30}
31
32// Create a Redux store
33const { createStore } = Redux;
34const store = createStore(counterReducer);
35
36// Subscribe to changes in the Redux store
37store.subscribe(() => {
38 console.log(store.getState());
39});
40
41// Dispatch actions
42store.dispatch(increment());
43store.dispatch(increment());
44store.dispatch(decrement());
xxxxxxxxxx
44
store.dispatch(decrement());
// Let's create a simple counter application
// Action types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
// Action creators
function increment() {
return {
type: INCREMENT
};
}
function decrement() {
return {
type: DECREMENT
};
}
// Reducer
function counterReducer(state = 0, action) {
switch (action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment