React Hook Concept Also Redux - reactjs

can I use Use state instead of redux?
Can I Manage all the state by use state ?

This question has a long and complicated answer, but I would suggest the first port of call would be reading up on the redux docs about how you might want to organise the state within your application.
TL;DR, it entirely depends on your situation, take a look here

Both are valid, but both have cases where they are better to be used, for example if you have a state you want to manage one level below, and is not used by other components on different hierarchy, then passing the state and it's handler as a prop is the better solution.
But some cases are more complex and require a lot of passing down of a prop through the components until it reaches the child that actually uses it, and. the parents of that child do nothing but pass it down, that is a smell of bad code.
Here it is beneficial to have it in a global state where the child can access it directly, without needed all of its predecessors to pass it down as a prop (also known as prop-drilling). Another case where this is useful is when multiple components need to access the same state, in different part of the system. It would be much cleaner to have it stored in a global state available for every component that requires it.
TL;DR, depending on your case, one solution is better than the other. Assess your situation case-by-case.

Related

useContext with immutableJS

I have an Object of data that I store as my context. It gets filled with API responses and I feel like performance-wise I'm doing something wrong.
I tried to look into ImmutableJS but there is no reference of combining ImmutableJS with ContextAPI. Is combining them together doesn't give any benefits? And if it does do have an example of to how develop such a thing?
Whether you use context directly, add redux or pass down props through your component makes no difference to how you use immutable. ImmutableJS simply makes sure that an object does not change unintentionally and that it can be checked for changes with fast reference equality.
The problem you describe could arise from the fact that your context object changes whenever any response data is modified. Therefore it would trigger a rerender on all context consumers (see caveats). I like Immutable and use it in a large project, but if I am correct, it won't make a difference, you would have to fix the root cause or handle changes with shouldComponentUpdate.
I suggest you look into redux (or some other context provider) or show us code.
Don’t try solving your problem by introducing a dependency. It won’t be a magic bullet.
From what you describe, your context object changes frequently and is causing your component tree to rerender too often.
Maybe try creating multiple contexts that are only relevant for parts of the app. That way rerenders will only happen with subtrees using specific context.

From OOP to ReactJs: Why I should remove the local State from a Component and move it to their Parent?

I would say that I have good experience with a lot of OOP languages. Most with Java. I've made full stack development with Spring boot and now i'm trying to learn React.
My point with all this is that maybe I'm to used to OOP languages so there are some "design philosophies" that I cannot understand.
I've started with this tutorial video:
https://www.youtube.com/watch?v=Ke90Tje7VS0
It's pretty great and clear but I have an issue in one part in particular:
1:47:55 Removing the Local State
To summarize the video, he makes an component called Counters that contains N componentes called Counter. This component Counter is just one number and a button that every time is pressed the value should increments by 1.
Originally, this value was stored as an state in the Counter component. This makes sense thinking in a OOP way. But then, in that chapter from the video he suggested to remove that state and mantain that value in the parent component, Counters.
And every time the button "INCREASE" is pressed, what is doing is calling Increment in the parent component. The value is stored in Counters. Not Counter.
Now, my question: Why not keep the VALUE state in the Counter component, and everytime is increased, inform the parent component that this happened?
How is this design philophy called? Any tutorial/book/video that explain this better for the people that comes from a OOP background?
Sorry is this is a dumb question. Thanks!
The goal of this is to have a "single source of truth". In other words, if this piece of state is only kept in one place, then it's impossible to have a conflict between different versions, because different versions don't exist. And this in turn means you don't have to devote any effort or code to trying to keep states in sync with eachother.
Now in principle you might think of having the child component be that single source of truth. But the way react is designed, props always flow from the top of the component tree to the bottom. A parent component passes props to a child component, not vice versa, so react makes it very convenient for the state to exist in the parent component and then be passed to a child.
As you mentioned, the child could notify the parent of changes, which would be done through a function prop. But in order for the parent to rerender and use this new data, it will then need to set state on itself (setState causes render). And now the state is being kept in two places, which is the thing we were trying to avoid.
The design philosophy is known as smart vs dumb components and it becomes more useful when dealing with larger state management libraries like Redux. The goal is to separate your logical components, those that deal with manipulating the state, interacting with other libraries like Redux etc. From view components. That way your view gets to be a pure function, reacting only to the parameters passed explicitly to it. This makes them extremely easy to test. And you only have to test that your smart components are passing the correct values to the view only components. Decoupling in this way makes testing smoother and prevents a variety of bugs that could otherwise be difficult to track down.

Using a closure to encapsulate state for React components

When passing data between two elements that are very far away from each other in the hierarchy of components, passing data through props can be tedious. In these use cases I've resorted to using Redux just because it is less to keep track of when there is a large amount of components.
What I've done in one little project is to use a closure to encapsulate state and export that variable and consume it elsewhere. I feel this is a an antipattern but it does work.
The way it works is by declaring some variable that is going to be modified within a component. This same variable is the imported from elsewhere and consumed from elsewhere.
Here is a small sample with what I am doing (just pretend there is a large component hierarchy): https://codesandbox.io/s/2R9RvYkN1
So my questions are: is there a better way to achieve the same results? Should we use a Flux implementation for these use cases? Is it ok to just pass props around through a large hierarchy of components?
As you stated yourself, redux solves this problem by providing an "App state" that's global to your app, which allows you to connect any component you want to that state.
Your "closure" is merely a poor-man's Redux, it's also a global state, only it lacks any of the features provided by Redux(unless you write them specifically).
let's CompA needs to re-render based on a click event on CompB, how do you do that automatically with a closure? you'd have to add listeners, check if a relevant state was changed and then re-render.
all these things are done for free by Redux, so I don't see any added benefit(except for not using redux, which can be a benefit in it's own).
If it's that important not to use redux, this can be "fine", yet very dangerous and I'd say it won't scale well.

Correct way to update owner state

I have two components, contact form, and input.
At this moment i pass onChangeEvent from contact to input as is described in many tutorials and its works fine - input update his owner state.
But there is way to pass 'this' from contact to input by prop, or context and then I can update owner state without passing onChangeEvent - but is this a good idea?
Is there another option to update owner state without passing onChangeEvent?
I believe you could technically do it, as a React component is a regular javascript object in the end, so you could pass it as a prop.
However, that's not a good idea in general, for various reasons:
It tightly couples the two components together. If you ever want to reuse the input component in another place, you'll need to pass in the exact same state.
Linked to this, it allows manipulation of the internal state of one component, by another component, which is a violation of good OO design.
You are right however, that things tend to become quite verbose when working like this. They also become hard to reason about when one has more complex trees of components passing props and change handlers between them.
One solution to the problem, is employing the Flux design pattern, and namely it's Redux implementation.
In Redux one has a single piece of global state, a plain object, of which components see pieces (sub objects). Components receive this state as props, and just render from it in a simple fashion. There's a set of actions which transform this state, and any component can issue such an action, as a result of user interaction. There's still the concept of "state", but it is reserved for truly local things, such as the state of a form before pressing the save button etc.

Is there a good rule of thumb for determining if a react component should manage it's own state or not?

I'm fairly new to react, and really enjoying it. In creating components, is there a good rule of thumb (or simple generalization) to consider when deciding if a component should manage it's own state or not.
As example (only as example), an input that gets different classes added based on state, like 'hover', or 'not empty'...
Would it be better to create a component that manages those states internally or just handle that wherever I'm rendering an input?
I know this question may be 'primarily opinion based', but I'm hoping to get a general feel for how to think about it.
Thanks in advance,
-Ted
This is a constant internal battle that you'll just decide on down the line and you're right that it's primarily opinion based (meaning no answer will be correct). However, I can share my own experience and the process I take to decide on how to split the logic of my components.
I think of these things:
How will having/not having that piece of logic affect unit tests? If the component would need too much setup to be tested, then I move some logic into it and away from a parent Container component.
How often will I reuse the component? If it's many many times, then I look at the types of Container components that would render it and, again, if it seems like too much boilerplate is needed, then move the logic.
Does the value change through its own behavior or based on outside queues? In your example of the hover, the behavior changes due to its own behavior so it feels like the className (a prop of itself) is reacting to the component itself.
Most importantly, do you benefit from removing the logic and placing it in the Container? If you think that other component could benefit from knowing the hover state of your input field, then you may want to put the logic in the container. Otherwise you're abstracting away too much.
Application state management libraries such as Redux will often suggest to use their libraries as little as possible and instead rely on internal state of the component. I mention this because as you figure out where to put your logic, you have to think that about the end goal, which is usually to create a web application, with multiple components working together. Abstract too little and you end up creating non-reusable components. Abstract too much and you have tons of boilerplate and configuration lying around that could be trimmed by using internal state.
Zeke has some absolutely great points. I'd just like to add my own guideline, which is:
If the behavior of the component is the same, no matter where it's used, and is not tied to the behavior of the app/environment at large, then state should be internal
otherwise, manage state elsewhere and pass in props

Resources