How to use shared component reference in React? - reactjs

I have a requirement where I have to render Component A twice in the Container, one at the top and one at the bottom.
Both the components should be in sync ,
changes made at one place should be reflected at other place,
Component should not mount twice as there's lot of API calls being made inside componentDidMount of Component A.
Is there any approach to do it, without lifting the state up?
Image for the above requirement

A component is an independent entity in react. It has it's own state and own set of variables.
If you don't lift your state to the parent and then pass to the component A.
It is not possible to use same component on same page twice with the same set of state without component being rendered two times.
You must lift state to their parent and then only it can be achieved or else it is not possible.

Related

React useState causes performance issues - the proper way to handle menu interaction

I have an app with a "menu". The "menu" is fairly complex, and the user can open small divs to set parameters that affect the app in real time. The app is structured as below:
Parent div with multiple useState instances to set parameters
- Menu Child Div
- functions to set those state variables are all passed to this div
- parent state is altered using these
- Main div where the results are displayed
- receives the state from the parent div and displays appropriately
The way that it works is that when the user interacts with the menu, the state is altered in the parent and that state change is then passed in the props to the main child div. This is causing performance issues as the app has to rerender everything when something changes in the menu and the existence of so many state variables may be a problem.
What is the best way to handle this? Using the useReducer function instead could be an option, but I am not sure that this alone would solve the problem. How do I make the main div respond to changes in the menu without everything having to be rerendered?
How do you handle interaction between your menus and your main div without having to re render everything?
Would the performance issues be solved by doing the following?
Parent div does not address state
- Menu Child Div
- interacts with redux state to change options
- Main div where the results are displayed
- reads in and reacts to redux changes
If you want a React component not to re-render unless the local state/props are changed, you may consider replacing your React.Component with React.PureComponent.
Whenever you're dealing with State that is being passed around between component orders, you may want to consider managing a global store. You can do this by using tools such as Redux, MobX-State-Tree, or Context API. This is especially useful if you're managing a mid-large scale project.
Resources:
https://ozmoroz.com/2018/09/what-is-purecomponent/
This resource has some great info on common React tools:
https://www.reactnative.express
And of course, there is always React's docs of which you are likely well aware of:
https://reactjs.org/docs/hooks-intro.html

Re-render logic for children of parent which updates muliple times per second

So I have a component which the state is updated multiple times a second by a child element.
To prevent over-rendering i use the shouldComponentUpdate on the other children to make sure they don't re-render too much.
The element of the state that is updated is required by another child further down the tree.
I would only like that child element to rerender, and not the intermediary children, again, to avoid over-rendering.
How could one do that?
I would only like that child element to rerender, and not the intermediary children, again, to avoid over-rendering. How could one do that?
You can't via the traditional method of passing the state down as props. A change in state in the parent component cannot trigger a re-render on the grand-child component C without triggering a re-render on the child component B first.
For a component to update a child, it needs to go through its life-cycle before it can pass down new props to it.
To my knowledge, the only way around this is to use a state management library, such as Redux or MobX, or use the React Context API and move that state variable there and then "consume" it in your grand-child component.
That being said, unless your tree is multiple levels deep and you don't see any performance issues, I would consider keep using shouldComponentUpdate() like you are already doing.

state vs props for scenario with separate view and data model

I'm building an application where I would like to provide separate views for same data.
In my current implementation, data is obtained by web service call and persisted in state of App component in App.js. App component hosts (renders) another component called StackEditor, which acts as a view for this.state.components in App component.
UI elements rendered by StackEditor can be moved around, and to synchronize state of App I do it as below:
<StackEditor
components={this.state.components}
onLocationChanged={this.handleLocationChanged} />
In handleLocationChanged I update the state:
handleLocationChanged(e, data) {
this.setState(prevState => {
// event data copied to state here
return {components: prevState.components};
});
}
As state is now updated, this forces StackEditor to be rendered again, as its property components is bound to state as components={this.state.components} (see in the code snippet above).
This all works, but now I started questioning if I'm doing it right.
Q1: Should I be using state instead of props?
It seems that location of component is mutated in principle, although from StackEditor point of view, it is immutable (I can decide that change is invalid and not to update the state in event listener).
Q2: Is it possible to share part of the state between 2 components in React?
If I somehow convert StackEditor from getting components from state instead of props, will I get notification on state changed by child component (StackEditor) in my parent component (App)?
Q3: Also, are props more convenient to use than state in general?
When I created another component following HOC guidelines (https://reactjs.org/docs/higher-order-components.html) I discovered that props are easily forwarded to "wrapped" component, but not state. If I provide a function to call back via property (as I did above), "wrapped" component can easily call it, without even noticing that it's "wrapped". I don't see how I can easily notify "wrapped" component about state change in "wrapper", without writing some extra code.
If you imagine your application to be a tree of components in a well designed app it's usually like this:
the leafs are stateless components . They decide how data is rendered.
the nodes are stateful components. They decide which components and data to render.
Q1: Should I be using state instead of props?
It depends on which category of components you have (node or leaf).
Q2: Is it possible to share part of the state between 2 components in
React?
If you feel that your app has a lot of state that mutates and needs to be used by several components spread over your tree you usually start to introduce an external state management library (e.g. redux). Components can subscribe to your store and become stateless as your store now handles the state.
Q3: Also, are props more convenient to use than state in general?
They solve different problems so you can't really say that. A stateless component is usually easier to understand but has no capabilities to control anything.
Also read Identify where your state should live and When to use redux.
All that is only a rule of thumb. A lot of the time you will have components that have both state and props because they control parts of your app but delegate other parts to their children.
This all works, but now I started questioning if I'm doing it right.
As far as I can see from the code you provided this looks pretty much as it has to.

Where do I put CRUD operations in a reactjs app?

The web is full of people telling me I'm doing react wrong. I'm sure they're right, since I've just started. A commonly referenced truism is that react is just the view layer. That's wonderful, but it leaves me wondering simply where do I put my other stuff?
I have a pretty straight-forward set of components which together show a list of nested data types and allow some editing, creation, and removal of the things. The components which consume the data have it passed in through props down the hierarchy from a parent that fetches the data. Should those read operations go somewhere else if it's "just the view layer"
What's the best practice for this, the idiomatic way, the react way? Should my delete operation be included with my delete button component? next to the read operation? somewhere else?
I suggest you to try some flux architecture. In this case it will looks similar to described below:
You call action on delete button click, for example actions.deleteUser(1)
Action calls appropriate API
Store connected to your component changes and component state changes
component re-rendered automatically
It depends on Flux that you prefer. The flow may be slightly different. I prefer reflux one
In react, data flows only from parent component to child component. I assume that your state is stored in the parent component, since you have create, update and delete in separate components. The state can only be changed by calling the setState() function on it. Therefore child components cannot modify the state of the application. This can be done only by having a callback function.
The delete function will be written in the parent component and will be passed to delete component as a prop. The delete component will then call the delete function (callback) which will call the setState() upon the state of the parent component and thereby altering the state. Never alter the state of the application without setState().
Hope this helps

State of child components in React

Should child components never have a state in React? I understand that state should be maintained by the "wrapper container" or parent container and it should have unidirectional flow. I have started with React and have a header container with upto 10 child components.
Let's say one of the child component is a Form with a submit button that can be enabled or disabled.
Should this child component not be able to have a constructor with state initialized for the button and be able to directly manipulate it or is it important that I maintain states as minute as this in the wrapper container "only"?
You should let the parent container manage the state of forms. I usually attach an onChange listener to each input and then when the submit button is clicked I call a function in the parent component to submit the value contained in the state for my form inputs. The form should only render inputs and do nothing else, basically a dumb component.
The purpose of React is providing a component system to front-end. It does not specify/enforce how state flow. People generally prefer state-less components because it is easier to share and distribute. However, front-end component can never be fully state-less + declarative.
In my opinion, you should feel free to use this.state to manage local state when you feel appropriate.

Resources