Reducers

What are reducers?

Reducers handle the logic that will happen to the state . Let’s say a user clicks a button — what happens next are the following steps:

An action type called "BUTTON_CLICKED" launches off an action with the payload. The action returns a plain object. All reducers will be invoked. The reducer with the type "BUTTON_CLICKED" will be further invoked to return the new state . The payload is passed by the action . All reducers by default return the state . The store listens for any changes in the reducers and holds the new state. The store passes the new state to our React views. React updates the view.

A lot of jargon — it’s easier to understand it in action.

We’ve made our store (#3) and now we’re going for reducers (#2).

You might ask, “Is this all necessary?”

No, it’s not necessary. You might even feel overwhelmed. But do not be discouraged. Redux is not as hard as you think once you understand all the jargon.

Shall we finish the reducers? Our store needs them.

We’re going to make a dedicated directory for the reducers called src/reducers . Inside the reducers directory we make an index.js file.

src/reducers/index.js

Inside the src/reducers/index.js , we import combineReducers from Redux. combineReducers melts all of our reducers into one reducer.

Why do we need just one reducer? The Store counterpart accepts only one reducer as an argument, the rootReducer.

Now we have a constant called rootReducer , which we export.

The Store accepts the rootReducer we just exported. We’re good to go!

src/Store.js

Are you wondering what your browser is telling you now?

Another big red error!

Don’t be alarmed — It’s just Redux trying to help you. If we read carefully, we see that we’re missing a reducer inside our combineReducers function.

Makes perfect sense.

Let’s make our first real reducer now.

Reducers have two arguments:

The current state , which we initially set to an empty Object {} . An action .

The reducer will always return the state.

Let’s import our app_reducer.js and pass it as an argument to the combineReducer .

As you probably know, we can pass objects as arguments to a function.

Right now, our state is called astronomy . Once we’ve called mapStateToProps , our data will be inside this.props.astronomy in our “connected” components.

Our browser stopped showing red — we must be doing something right!

We’ve created our store and our reducer . Now we must create our action and, finally, wire it up with our React component.

It’s always important to see which problem we’re trying to solve — it’s fetching the astronomy data from the NASA API.

We’re slowly but surely decoupling our state from React and letting Redux handle the state.

Next up: Actions!

Check out Redux’s documentation if you’re interested in reading more about Reducers.