Static Class Variables ES6 - javascript

Is it a good idea to use static properties in ES6. Some of my colleagues believe that it is a bad idea, but I did not get a good explanation as to why it was so.
I am building a ReactJs application, and I use redux wherever necessary, however, when I want to share some data with all the components in the app, can I use static class properties?
In my case it's we want to share the value of a variable called ThemeName across all components. Note that the components do not listen to changes to this variable. It just takes the value of the variable when it loads.
It actually works without any issues, yet somehow I have this feeling that it could be anti patten, can someone please explain the issue here, if any?

It is not a good idea to use static properties with React for a few reasons:
Class properties aren't tapped into the React's lifecycle, so unless these properties are never, ever going to change, static properties are going to be too inflexible.
React itself if moving away from classes in general, so if you are new to React I would recommend not using classes at all. You can read more about the motivation behind this in the official React docs
React cooperates with other mechanisms for accomplishing what you are trying to accomplish, whether that be Redux, or Context

Related

Can you bypass state management for simple objects? (global shared state)

Can you globally instantiate a class and that will be reliable on react-native? i.e.
// logs.ts
const instance = new Instance()
export { instance }
// something.tsx
const Component = () => {
instance.method()
...
}
If method were to increment a property by 1 would that property always have been incremented the number of times method was called throughout the project?
The primary benefit here is simplicity. For example, it's easier to define
class SomeClass {
constructor(properties){}
addProperty(key,value){ this.properties[key] = value }
}
than it is to do the equivalent in redux. Why don't people do the above more often?
Just changing the value on some object will not result in state changes/cause a component to re-render. You still need a state provider to have the state set to. If you want to change the state of that Provider you'll need to run setState (or dispatch and useReducer) which means you'll need to pass the dispatch of that function around to all of its children. As your app grows larger you'll definitely want to/need to useReducer and perhaps even several providers, you'll be re-implementing redux which is only about 200 lines of code anyway. So the question will become why did you re-implement redux which is such a popular library that most people know exactly how to use and there is plenty of documentation for, in favor of your homegrown version of redux which doesn't provide much additional value?
In redux a primary benefit is the tooling like redux-logger, redux-thunk, redux dev tools and time travel and others etc which allows you to replay the changes made or undo them. Sure it is easy to modify an object but using redux allows you to testably and consistently see how an object (the redux state) changes over time and undo them. You can test that action creators return the correct actions. You can separately test that given specific actions the reducer behaves as expected and replay that with mockStore. In short, using redux you get the enterprise version supported by a large community of experts who have helped improve and implement essentially the simple class that you demoed.
Although you can do this, it breaks away from the point of redux. Redux is meant to be a centralized state management store, and therefore, allow components to
access shared state from a single location and analyze shared states, because it comes from one place.
track history and actions taken to get state there
makes maintaining, debugging and collaborating on a codebase
much easier.
Doing the first option, all these benefits are lost.
That said, if you have multiple components in one file, and you want them all to share that same global state (not exporting it), using the class constructor to do so isn't a big deal, as long as the project isn't being worked on by other developers.
However, it would make more sense in that case to make an overall component class, and pass state down, as that is the point of React. Declaring a class outside and trying to manage state in the first way, would be a declarative approach, which is what React doesn't want developers to do (i.e there is a better way, like creating a hierarchy of components). That way, components re-render on a change in value, and no weird bugs arise

Is it possible to store instances of custom class in Vuex/(Vue data)?

According to vue documentation, it is not possible to store anything besides plain objects. (https://ru.vuejs.org/v2/api/#data). I always use vuex as a DI container, I see it from this point of view. It keeps vue away from my application business logic, and makes possible describe business rules only using JS with no dependencies. But that approach breaks vue dev tool, and for some reason not all tests pass.
Is there a way to circumvent this restriction? For example class instances can be created in getters rather than in mutations. But it does not work for me because some constructors of my classes have side effects (It's not a best practice, but that what i have).
You can absolutely store class instances in the store state.
I generally store arrays of models, which is really useful to keep logic in one place.
Something like:
Api.load('/api/users').then(res => commit('users', res.data.map(User.create)))

React App without state and props

I would like to know if it's fully consistent with the React principles.I made a React App without state and props.I've put pure javascript only inside componentDidMount e.g.
componentDidMount(){
const first = document.getElementById('first');
const second = document.getElementById('second');
function funk(){
console.log(first.innerHTML);
second.innerHTML = "Arrr";
}
funk();
}
Of course it's just an example, my app is far more complex.
Technically speaking, You can (as you may already know).
Should you do it? A big and glowing NO!.
With this approach of targeting the DOM directly, you are bypassing and missing most of the goodness that react has to offer with the Reconciliation and The Diffing Algorithm.
If you really (really) need to target the DOM, you can use react's ref API.
And you can see in their docs it's should be used sparingly :
Don’t Overuse Refs
Your first inclination may be to use refs to “make
things happen” in your app. If this is the case, take a moment and
think more critically about where state should be owned in the
component hierarchy. Often, it becomes clear that the proper place to
“own” that state is at a higher level in the hierarchy. See the
Lifting State Up guide for examples of this.
Yes and no
Yes, you can use it in some cases for utilizing complex jQuery plugins integrating react as a part of your project and so on...
I know that there are lots of haters of such approach but we should also understand business if it's possible to achieve a goal without spending 40-80hrs for coding it yourself - go for it.
No, you should not do any DOM manipulation in component live cycle methods unless you are very good with react and completely understand how things work internally in this library.
Changing DOM in such way will most likely cause performance issues because your components will not be able to utilize shadow DOM, as a result, your components will perform DOM manipulation after every change and could potentially slow down the application.

Custom events versus callbacks in ReactJS

I'm new to ReactJS and I'm trying to figure out how to store and manipulate global state. For example, I'm writing an editor app that has some global state: selected color/background, active tool, current selection, etc.
I'm thinking about having a root interface component to store this information, and I'm ok with explicitly passing the state around using properties. I guess the idiomatic way for a children component to change global state is calling a callback received from the parent - personally I find this a bit annoying.
Instead, I'm firing custom events at the children and setting listeners on the parent. So far it is working really well, but I looked at a lot of sample code and never saw people using this pattern.
Is there any practical consequences I should consider?
Flux is great for manipulating global state because the Stores are globally accessible. Globals are known to be bad, but the way you interact with the Stores is through Actions. Actions make the state predictable and localized. So even though the state storage itself is global, Actions make the state interactions very local. At work we tend to do both reading & writing through Actions, so every state change is an "event" that leads to easily programmable behavior.
I really wouldn't compare Flux to Angular as their principles and flows are entirely different. Suggest you try Reflux.

EmberJS - Calling components methods from outside with a couple solutions (call for discussion)

The following is from an issue I posted on EmberJS GitHub, but Stack Overflow is better suited for a discussion than GitHub.
I am building a few complex components at the moment including composite components and I hit a roadblock with the extreme isolation components live in.
There are several cases where I don't need the components to trigger an action on a controller, but where a controller needs to trigger a behaviour change on the component.
Problems is that the components don't know about the controller and the controller is not creating the components either: they are defined in a template.
I kind of solved the problem by subclassing the Ember.Component class to offer a way for messages to get through components.
The new component subclass breaks the on purpose isolation of components that shouldn't know about the outer controller.
The 2 less invasive options I found to make component methods calls from outside are:
Cache component / name of instance pairs in a global array like
App.components, then call a component method with
App.components['name'].method()
Trigger events from outside, register and handle them in the
components. However in that case I am passing an eventSource object
to the component, often a controller like so: {{my-component
eventSource=controller}}
My question is about how could we solve this problem in the most elegant and less invasive way possible for components ?
For achieving composite components, using the components like lego pieces, it seems impossible to me at the moment to see how we can achieve that goal without breaking the components isolation.
Any input, ideas, solutions, discussion is very welcome.
Note: By the way, the first method that breaks the component isolation is inspired by the work done on the ember-bootstrap components: https://github.com/ember-addons/bootstrap-for-ember
The author had to solve the same problem of being capable of triggering methods inside the components from outside.
Another note: Just for the record, another way to access a component is to use Ember.View.views['name'] where name is a view name you gave to your component. However I feel dirty to make such calls, even more from a controller.
In general, I would try to solve this by binding properties to your component, which could then change according to computed properties or observers based on those properties.
For instance, instead of trying to call a method like deactivate on a component, bind a property such as active to a property in the template:
{{my-component active=formEnabled}}
I'm hesitant to recommend passing an eventSource to components as a general solution (like your {{my-component eventSource=controller}} example). I imagine this could work with a class or mixin that just emits specific events and is tightly coupled with your component, but I'm struggling to come up with a use case that justifies this approach.

Categories