Vue, React! Differences in component's state

Published on 2021-11-24 08:05

Available in:

One of the harder parts of getting into React after a multi-year break is React's state. As my current framework of choice is Vue.js let's compare them.

Vue

In Vue.js the component's state is stored in data and computed sections of component. Here I choose to the word section because data is a function which returns an object with state variables and computed is an object of other objects and/or functions.

React

In React the situation is a bit complicated. React in class based components stores its state in a this.state object. It allows for complex state similar to Vue's data function. But unlike Vue it can't be updated directly.

In React's functional components, one has to use Hooks to update the state. For simple states, my rule of thumb is five state variables, is to use hook useState as in:

const [state, setState] = useState(initialState);

This is a definition for only one state variable. So for more complex states it can become less readable fairly quickly

For more complex states there's a hook called useReducer. It looks like a light version of reducer in state management libraries like Redux or NgRx. At the same time it can act like Vue's computed object as well.

The code for initializing a reducer is similar to the one of useState:

const [state, dispatch] = useReducer(reducer, initialCount, init);

Comparison

Let's say we have a list of colors in out state and we also want to have in our state number of those colors. In Vanilla JavaScript it would be represented as:

const colors = ['red', 'green', 'blue'];
const noOfColors = colors.length;

In Vue's state it would represented as:

data() {
  return {
    colors: ['red', 'green', 'blue'],
  }
},
computed: {
  noOfColors() {
    return this.colors.length;
  }
}

Alternatively we could utilize getter pattern and it would like this:

computed: {
  noOfColors: {
    get() {
      return this.colors.length;
    }
  },
}

As mentioned above, something similar is possible in React with the Reducer hook. First we need to create a function, for brevity let's call it reducer(). Inside the function we'll have a switch for dispatched actions which reacts on them and updates the state.

function reducer(state, action) {
  switch (action.type) {
    case 'UPDATE_BOOKS':
      return {
        ...state,
        state.colors: action.payload,
        state.noOfColors: action.payload.length,
      }
  }
}

Conclusion

Vue and React are similar when it comes to having state and managing it. In my opinion Vue's is a bit more intuitive but at the end of the day both do its job.