Search⌘ K
AI Features

Writing our first Redux parts

Explore how to write your first Redux actions and reducers to manage state updates safely without mutation. Understand connecting Redux to React components and dispatching actions to update the app state. This lesson teaches you to structure your Redux logic properly for predictable state management in your weather app.

Our First Action

Let’s write our first action! We’ll start with the location field, since it’s a very typical example. An action function in Redux returns an object with a type and can optionally also pass some data along the way. Our changeLocation action looks like this:

function changeLocation(location) {
  return {
    type: 'CHANGE_LOCATION',
    location: location
  };
}

This action thus has a type of 'CHANGE_LOCATION' and passes along some data with the location property.

That’s nice and all, but this won’t change the state automatically. We have to tell Redux what to do when this action comes in, which we do in a so-called reducer.

A reducer is a simple function that takes two arguments, the current state and the action that was dispatched:

function mainReducer(state, action) {
  return state;
}

Right now, no matter what action comes in and what data it has the state will always stay the same – that’s not quite optimal, as nobody will be able to work with the app! Let’s change the location field in the state based on the data in the action with the 'CHANGE_LOCATION' type.

function mainReducer(state, action) {
  switch (action.type) {
    case 'CHANGE_LOCATION':
      state.location = action.location;
      return state;
  }
}

What we’re doing here is mutating the state. We assign state.location ...