I have a JSON, and in it there are some fields that I need to calculate.
Where is the best place to do it?
Currently I have set it in:
componentWillMount: function () {
//Iterating over the JSON object
}
All my values are calculated and then the render is called. It works fine. I just wonder am I doing the right thing?
It depends. Are you mounting and umounting that component a lot? Are the calculations heavy?
What you are doing right now is probably fine, as you've said. If you really want to separate the data and calculations from the component you might want to look at redux and reselect
Yes, You can do all your calculations in componentWillMount of your json.
You can then set the state accordingly because setting the state in componentWillMount wont cause a rerender infact your render method will receive the updated state.
Related
I have an application that shows and manipulates users' information in a table with many columns. The user model has quite a few deep nested properties, each table column represent a property. To better explain, I created this simplified app at stackbliz. The real application has more columns and is relatively organised into more layers/components.
Basically, each column is a component that has an #Input person. While Location property value is changed by clicking itself, another component LOS needs to be aware of it and change its text colour, if location becomes 'J'.
Normally, this isn't working as the person reference of each #Input is not changed, so the change detection is not firing.
Please ignore the pipe used as it's just a way to show one component has to react if a property is changed in another component. I can mark it as impure but it seems not a good way as it will run too many times unnecessarily.
Also, I know I can make it work by using getter or a function to read the property in another component template, I have included the code as comment in stackblitz app. But it can unnecessarily run many times as well.
Question
I wonder if there is another better, cleaner and intuitive way to notify nested property changes between components. It could be a better way of organising the object and its property, passing them to different components, or other techniques that don't bring performance overheads.
Thanks in advance
Component Structure
You need a a RowComponent to segregate each row and its data and coloring of the LOS column (which may differ between rows).
After adding this component, I would not use LocationComponent or LengthofstayComponent as there is not much to them and your code will become cluttered with passing values between them.
Implementing the color changing
I recommend using a BehaviorSubject, a corresponding Observable and the async pipe. Every time the async pipe, emits, a change detection cycle will be intiated.
In RowComponent add:
showColorSubject = new BehaviorSubject<boolean>(false);
showColor$ = this.showColorSubject.asObservable();
If we call next on the Subject in changeLocation:
this.showColorSubject.next(this.person.location.code === "J");
then showColor$ will emit true/false accordingly in the RowComponent template where we use the async pipe to selectively enable the color class:
[class.color]="showColor$ | async"
Stackblitz
https://stackblitz.com/edit/so-color-row-cell?file=src%2Fapp%2Frow%2Frow.component.html
(Formatting is messed up but I'll leave that to you)
Sorry for asking without particular code examples for they may confuse with complexity and lead away from the point.
Let's say we have an array of records in the redux store that is represented by a list of connected react elements.
Saying "connected" I mean:
export connect(store => {/* list binding here */})(RecordsListComponent)
Then some action dispatched on store instantly removes a record and the list component is updated (re-rendered).
Now I have an intention to animate deleted records so they disappeared from DOM with a delay. What's the best (clear, compact, flexible and reliable) approach to make this?
One of obvious ideas is to use useEffect and useState hooks that will allow to keep the previous state of the list and analyse the diff with current state in props.
So the list component will be able to internally determine intermediate records' states (spawning, present, vanishing, etc.) and change them at it's own discretion.
Though, I don't know if this approach will be expensive on large lists...
I've a list (immutable.js) in my store containing multiple objects.
This list is displayed in a component as a table with rows. Those rows are subcomponents displaying one single object. One attribute of those objects should be editable. So onChange() i dispatch an action which should change the attribute of that one specific object. As we should never ever change the state, i return a whole new list with just that single object changed. But because the whole list is a new list object, the table component gets updated every single change. this leads to a really slow working app.
I've just looked at the official todo app example and inspected it with the Perf addon. Realising that they also rerender the whole todos-list on every change (mark as completed, unmark). How am I supposed to fix that?
The biggest factors that will impact your list rendering performance are heavy rendering cycles and expensive DOM mutations. Make sure that your list items are as efficient as possible when they re-render. Done properly, this will make a big difference.
You have a couple of straight forward options.
Break your rows out into their own component (if not already done) and optimize the render and update cycle.
Use a library such as react-virtualized to help with list/table/grid performance.
I need to know component's width in render method, but getting DOM elements in render method is not possible.
Solving problem I found this article. The problem in article is the same as mine.
Solution:
save component's width to state in componentDidMount method.
subscribe to window resize event and update state.
So I can get component width from component's state.
Anybody knows another approach to solve this problem?
Thanks.
Well, you don't have to save the width in state, you could grab it each time with ReactDOM.findDOMNode(), but this is about the best you're going to get. You can't update in render for two reasons:
your DOM elements are currently being rendered but don't exist yet
Even if they did, triggering an update in render is an easy way to trigger an infinite render loop.
Tldr: Just go with the method you have, that works just fine
Suppose we have two sibling react components called OldContainer and NewContainer. There is a child component inside OldContainer that contains a <video> tag, and the video is currently playing.
The user can now drag the child component (with the video) and drop it in the NewContainer, and they expect the video to keep playing while it's being dragged and after being dropped.
So the video appears to stick to the mouse position, and when dragged and dropped in the new container, it animates to its new position (again, it doesn't get paused).
How would you implement this? Can we implement this in a pure way (in line with the spirit of pure functions)?
Clarification: I could have used some other element instead of a video tag for explaining this problem. A NumberEasing element would be a better example, since it would require the props and state of the component to be preserved during and after the interaction.
Update 1: Code examples obviously would be nice, but what I'm mainly looking for is just a general description of how you would approach this problem in a "functional" way. How do you keep your view code simple and easy to reason about? Who handles the drag-and-drop gesture? How do you model the data that's fed into the views?
Take a look at this library : react-reverse-portal
What is it that you want to preserve? Is it Javascript objects that the component holds as state, or is it state in the DOM (like how long a video has played, or text selection in an input box)?
If it's just Javascript objects as state, you're better of moving the source of that state to another service (something like Flux). That way, it doesn't matter if the component gets recreated because it can be recreated with the state that was there before.
EDIT
The way to keep your view code simple and easy to reason about is to not keep state inside your components. Instead, all data that the component needs should be passed into the component as props. That way, the component is "pure" in that it renders the same output given the same props. That also makes the problem of wanting to reuse a component instance a non-issue, since it doesn't matter when the same input gives the same output.
For drag and drop, I'd suggest looking at: https://github.com/gaearon/react-dnd.
How you model the data you pass to view components is up to you and the needs of your application. The components shouldn't care, they should just expect to get data passed as props, and to render them. But the popular approach to dealing with this is of course Flux, and there are many libraries that implements Flux in different ways.
SECOND EDIT
Regarding if you have a subtree with hundreds of components that you want to move: I'd still start off by making the state external (pure components), and render that tree in a new place. That means that React will probably recreate that entire subtree, which is fine. I wouldn't deviate from that path unless the performance of it turned out to be horrible (just guessing that it might be horrible isn't enough).
If the performance turned out to be horrible, I would wrap that entire subtree in a component that caches the actual DOM tree and reuses it (if it gets passed the same props). But you should only do this when absolutely needed, since it goes against what React tries to do for you.
THIRD EDIT
About gestures: I'd start out with listening to gesture events in componentDidMount, and in the event callback call setState on the component with the coordinates it should have. And then render the component in render with the coordinates given. React won't recreate the component when you call setState but it will re-render it (and diff the output). If the only thing you changed was the coordinates, it should render fast enough.
If that turns out to be too slow, like if the subtree of that component is huge and it becomes a bottleneck to recreate the subtree of vDOM, I'd reposition the DOM node directly in a RAF-loop outside of Reacts control. And I'd also put a huge comment on why that was needed, because it might seem wierd for some other developer later.
Create a new variable using const or var. Put the instance of data using rest spread operator, update the necessary data to pass and send the data to the component without mutating the state of component.
Just like:
const data = {
...this.state.child,
new_data : 'abc'
}