Mark As Completed Discussion

Actions and Reducers

In Redux, actions are payloads of information that describe changes to the application's state. They are the only source of information for the store. Reducers specify how the application's state changes in response to actions sent to the store.

Actions are plain JavaScript objects that have a type field and an optional payload field. The type field is a string that describes the type of action being performed, while the payload field can contain additional data that is necessary for the action.

Here's an example of defining actions and a reducer in Redux:

JAVASCRIPT
1// Let's start by defining some actions
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// Dispatch actions
37store.dispatch(increment());
38console.log(store.getState());
39
40store.dispatch(decrement());
41console.log(store.getState());
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment