I have been in charge of setting up a new frontend at work for a new project. Initially I created a new React app using create-react-app, and decided to use React Context API for handling data in the app. I would fetch data when loading the page, save it a in a global state, and then populate it throughout the app using Context. This worked in the beginning, but I quickly realised that It got quite complicated handling a lot of data after a while. I also stored information about ui state in at a Context level, for things like if sidebars and navigation menus are open.

We also wanted to be able to listen to events sent by our backend API to then update state with new data throughout the app. Since we also didn’t store every entity at the Context level this got quite complicated. We started having multiple sources of truths and manually managing a lot of state updating. I decided to start looking towards Redux — a global state management tool I had been using at my previous job. I hadn’t had a lot of good experiences with it, and I was quite ___ towards actually taking a look at it again. However, I spun up a playground for trying it out, watched some tutorials, and hashed out some strategies. Here’s what I learned.


Redux is easier than we think

Redux has this sort of mist around it, as if it’s some sort of black magic library that only a subset of people in the frontend web development industry actually understand. I think we need to get rid of this assumption — since Redux is just a tool for lifting our data state to another layer in our application — away from our components.

Concepts

Redux have some concepts with naming that can be quite deceiving and sound more complicated than they actually are. These are the main concepts in Redux.

Store

The store is where all data is eventually going to be stored.

const store = createStore(reducers)

Reducer

The reducer is kind of the exchange point for the incoming actions.

switch (action.type) {
  case 'GET_TODOS':
    ...
  case 'CREATE_TODO:
    ...
  CASE 'PATCH_TODO':
    ...
  case 'DELETE_TODO':
    ...
}

Action

Actions are the triggers for fetching, patching, deleting and adding to state.

function createTodo(todo) {
  return {
    type: 'CREATE_TODO',
    payload: todo
  }
}

Full example

Let’s try a real example. I’m not going to build a simple counter app like every other Redux tutorial does, since it’s not very real case. Let’s build a todo app that actually updates data in a database, and uses Redux for its frontend data layer management. Let’s start by creating a new React app and installing some dependencies.

#web-development #redux #react #redux-thunk #javascript

How I Finally Understood Redux
1.35 GEEK