A Vue Developer’s Guide to Redux

Ayushman Gupta
Bits and Pieces
Published in
6 min readMar 6, 2022

--

If you have worked in the front-end scene for a while, you must have come across myriad state management tools. Some of these tools are simple and try to solve only a specific problem in an elegant manner while others have some complexity that in turn benefits scaling the app.

Under this spectrum, you will find Vuex somewhere in the middle and Redux on the far right. Since the majority of my projects were based on Vue, I used Vuex a lot and it was about time to move out of my comfort zone and tip my toes in the waters of Redux.

First of all, let’s understand what state actually means in a Front-end world. We can say, a reactive state is basically a variable that once changed will re-render a specific part of the UI.

In a typical vanilla JavaScript, it becomes an increasingly challenging job to handle a state change. Although it is possible to do so using JavaScript proxies, which is a topic in itself and you can explore more about it here.

As the complexities of the app grow, reactive states with only JavaScript proxies become cumbersome to manage. Most JavaScript frameworks like React, Vue and Angular try to solve this reactive state problem.

💡 To tackle the complexities of a growing codebase, consider adopting a component-driven approach to developing your applications. And you can do that using open-source tools such as Bit. With Bit you can extract reusable components out of your codebase and use across multiple projects. Learn more here.

Get started:

Vuex

In the Vue ecosystem, the most popular state management library is Vuex. Still, there are many great alternatives such as Pinia, xState etc but we will only talk about Vuex as this is the most popular one and is suggested by Vue.

Vuex is based on something known as the Flux state management tool. It was a tool that was developed by Facebook to handle state in their front-end projects. If you’d like to learn more about Flux you can find it here.

Vuex tries to implement methodologies set up by flux and give us an abstracted tool that lets us perform state management without worrying much about the intricacies.

In Vuex you have a global state. But you can’t access/mutate state directly. You need to follow some procedures. If you want to change some state you need to dispatch actions. An action is an async function where we either fetch data from an API or perform calculations. At the end of that action, after we get the values we can commit the changes using mutation.

A mutation is an impure function that receives the state as well as the argument passed by the action. Now mutation can alter the state with some new value.

After committing the changes we need to access the new value from the state. For that, we can fetch it directly but the convention is to use getters that are pure computed functions that get the state in the argument and return a particular part of it.

Whenever the value changes, we will get the updated value via this getter. Since these getters are computed they are optimized, so they are only executed when the variables used inside that function change.

Redux

Redux also use the agnostic integration of the Flux system which enable us to use it with Vue, vanilla JS or any JavaScript library. In redux, again we have some initial state defined in the store.

Now the question is how will we mutate this state? For that we have actions. These actions are very different from Vuex’s actions.

In Vuex we defined business logic here, but redux actions are only simple objects that have two properties — type and payload that tells the reducer how to change the state.

Now this dispatched action will trigger some reducer that in turn will change the state.

Reducers are functions that receive the action object. Now inside this reducer, we will have to check the type to perform an update.

One thing to note here, the store object is immutable and you can’t change it directly. So how we will update the store? To update the state we need to return a completely new store object with the updated value.

We can use Immer, a package that allows us to mutate the object in the store. But technically it makes sure that we return a new object in the end.

Making our life easier with Redux Toolkit

Using redux is great, but we have to make some additional configs to make sure that we use it correctly.

Another alternative is to use Redux Toolkit, it is an opinionated way of using redux and takes care of some initial configs.

In the redux toolkit, we can create slices. These slices are basically modularized ways to access/update the state. In the end, all data in the store is stored in an object.

But we can create slices in this object to have separation of concerns.

A slice takes some arguments, it takes name to namespace slices, initial state, reducers and “extraReducers”. Reducers are synchronous functions that update the store. We don’t need to cover “extraReducers” but they simply allow createSlice to respond to other action types besides the types it has generated.

As I have stated before, redux is synchronous, for anything asynchronous we have to a middleware thunk which enables us to create async functions. In a normal redux project we had to config it manually but the redux toolkit has thunk out of the box.

We can define a function that returns a function that gets a dispatch argument. With this, we can perform any async task and in the end call dispatch to store it synchronously.

Now we can register these slices using the “configureStore” function provided by the Redux Toolkit. We pass the imported slices and give them a name.

So counterSlice reducers and state will be namespaces under counter. In the end, we need to export the store and use it in the Provider HOC component at the root level only then our components can access these states.

React-redux package gives us useSelector hook which we can use to get the state and useDispatch hook to call the reducers and action creators to change the state.

Conclusion

“If the only tool you have is a hammer, you tend to see every problem as a nail.” — Abraham Maslow

This is a quote by Abraham Maslow which refers to a concept commonly known as the ‘Law of Instrument’ or Maslow’s Hammer. It refers to an over-reliance on a familiar or favourite tool. Redux/Vuex can be very useful state management tools at times, but over-reliance can result in approaching problems in ways that are not always helpful or even destructive. So it always helps to have a basic understanding of a number of these tools and carefully contemplate the requirements before integrating one into your project. See you next time.

Build composable web applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and speed up, scale, and standardize development as a team. Try composable frontends with a Design System or Micro Frontends, or explore the composable backend with serverside components. Give it a try →

https://cdn-images-1.medium.com/max/800/1*ctBUj-lpq4PZpMcEF-qB7w.gif

Learn More

--

--