Is it a bad practice to build your own state manager instead of using Redux or Context API?

Viewed 109

I am struggling to understand Redux or work with the Context API, so I built this simple class:

import React from "react";

export default class X extends React.Component {
  constructor() {
    super();
    SM["set" + this.constructor.name] = function (obj) {
      this.setState(obj);
    }.bind(this);
  }
}

So if I have a component (e.g. ) whose state needs to be set by other components, it will extend class X and store its setState function in a global object called SM (state manager). So using SM.setCar({/state object/}) will call the this.setState of the component Car.
There's much less headache for me compared to Redux or Context API. The question is: is it a bad practice? Am I going to have fewer opportunities if employers see this in my code? If yes, why is it a bad practice?

1 Answers

You should in general never create a class extending React.Component that you do not plan to directly use as a component. While these are "classes", they should not be used for inheritance. Class components are just a syntax that is used for React components, but you should not really use all "class features".

Also, just to make sure you are aware of that: at this point, class components are pretty much-considered legacy. Most of the ecosystem is moving on to hooks and in one or two years you might have problems finding new libraries that support legacy-style class components, not to mention that using "class features" like class properties will get even more problematic in the upcoming React 18.

All that said: Generally, you could do such a thing (creating your own solution, not the inheritance pattern you were going for). But you probably should better take a look at existing libraries so you don't have to learn all the "lessons learned" of existing libraries the hard way yourself.

Alternatives to Redux would be MobX, Recoil, XState, Valtio or Zustand, all giving you a different mental model to use.
Context on the other hand is not suited for state handling as it requires a lot of manual optimizations and even then has performance problems that cannot be solved in current React. It is simply not made for state, no matter what countless tutorials are trying to tell you.

But you could also give Redux a second chance. As you are using class components, there is a good chance that you also have been following quite outdated Redux courses - modern Redux has gotten a lot more simple over the last few years. If your course showed switch (action.type) { case... in reducers or connect and mapStateToProps, it was an outdated tutorial that does not reflect modern Redux at all. If you want to take a look at modern Redux, the best way would be to follow the official tutorial: https://redux.js.org/tutorials/essentials/part-1-overview-concepts

Related