From my experimentation, if you have an object as react state (let [state, setState] = useState({})), and you do something like
setState(s => {
s.a = 42;
return s;
})
It will not re-render components that depend on s.a.
If on the other hand you do
setState(s => {...s, a: 42});
It will re-render all components that depend on any field of s.
So it seems to me like it really only looks at whether the returned object reference of the closure is the same as the state it already has or not and makes a binary choice whether to re-render everything or nothing.
Is that correct?
Is there any way to update state in a way that makes it only re-render things that depend on e.g. s.a?
CONTEXT, if it helps: I need this for my application because performance is becoming impractical. My application retrieves JSON information from and API endpoint, which contains a list of 'fields' that describe input fields that the user can use to input data. When the user is done, the application submits this data in a single json. So all input components are controlled, through a single functional state that holds one property per field (I need to be able to programmatically update some fields sometimes). Performance is prohibitive because all fields (quite many now) are updated/re-rendered every time the user types a character in one of them. I sadly cannot create a new state for each field because the amount of fields is not known in advance.
As a note before I begin, this is not okay, and does not work in general. Treat all React state/props as immutable, otherwise you'll have issues.
setState(s => {
s.a = 42;
return s;
})
There is no way to selectively re-render your component, the reason why that mutation on setState doesn't re-render children that depend on s.a is because your component doesn't re-render at all when you update like this because the reference of s doesn't change, so react doesn't see that there's a change.
The only way to make children not re-render when parents re-render is to use React.memo, PureComponent, or shouldComponentUpdate. And those have to be applied to the children rather than the parent.
When does React re-render child component?
Related
At the top of my component I define a variable with useRef like below.
const data = {
item1 : useRef (null),
}
console.log (data['item1'].current?.srcObject)
Now as the logic proceeds through the component the value for item1 is set up. The ref is attached to a video element. And at certain points the component re-renders.
The console.log prints the value of the srcObject upon the first re-render and the second. But on the third that value is lost. The srcObject is not explicitly changed in between the re-renders.
I don't fully understand refs but I'd like to know how these values are retained or destroyed. Of course I get that they maybe case specific but I'd still like to get the general idea.
You probably want to instead do const ref = useRef({item1: ...}) and reference the current value as ref.current.item. Your object is getting re-created every render.
If you put the object inside the ref, ref.current will be the object, and that object won't update or change with react renders. That's what refs are for, values that you can update independent of rendering, that also stick around for the lifetime of the component.
I've been reading React's Quick Start documentation;
Whether you declare a component as a function or a class, it must never modify its own props
This is a "pure" function, because it doesn't attempt to change its inputs, and always returns the same result for the same inputs:
function sum(a, b) {
return a + b;
}
This in an "impure" function, because it changes its own input:
https://codesandbox.io/s/9z38xv4x7r
function SayHi(props) {
props.name = "Jim"; // TypeError Cannot assign to read only property 'name' of object '#<Object>'
return <h1>Hi {props.name}!</h1>;
}
Why are React props read-only?
A component should manage its own state, but it should not manage its own props. props is essentially "state that is managed by the component owner." That's why props are immutable.
React docs also recommends to treat state as if it's immutable.
That is because by manipulating this.state directly you are circumventing React’s state management, which can be potentially dangerous as calling setState() afterwards may replace the mutation you made.
You may think of React component as a function of its props and state. As you advance through the docs, you'll find that this is the case, as most functions in the React component life cycle have signatures of the form (prop, state) => { //code }.
React docs define props as any arbitrary input given to a component, and the component will render something based on the props ( and sometimes based on state too, if it is a stateful component ). So props is like something that is given to the component for say, reference. Imagine it this way: you are a component, and your parent component gives you a reference book, containing some rules on how you must behave ( a.k.a. render ). Two cases may arise:
You are dumb (stateless): You just read the book, and behave so.
You are smart (stateful): You read the book, and then note some things in your notepad, that you may view, update or delete. You may even take copy down content from the book to your notepad, and then edit the notepad.
Either way, you may not update the reference book given to you. Only the parent component can update it ( example, give you another book, or change its content ).
I don't know if this is a correct representation, but React components work in a similar way. You'll get the hang of it soon. Make sure you read Thinking in React too. Happy coding!
The props of a react component is aimed to store values and functions from its parent component. It's just the pattern, props are immutable. If you want to have a variable that would be mutable, then store it in the state of the component. States are mutable.
Documentation says
For example, this will not re-render a component:
// Wrong
this.state.comment = 'Hello';
Instead, use setState():
// Correct
this.setState({comment: 'Hello'});
But, there is no answer for the Why? What is the justification for using the second one is correct?
When you use such a high level framework, like React, they don't bother explaining to such detail why because it's far too complicated for a simple article. Understanding why would require a deep understanding of React and how the vanilla JavaScript works under the hood. Looking at source code is an option for you, but life is easier when you take their docs at face value.
The virtual DOM:
React keeps a copy of the previous state of the page. It uses it as a reference point when it decides on what should be repainted and what shouldn't. When you click on a button, the entire page doesn't need to repaint the entire DOM to values that are completely identical, but what's kind of shitty about JavaScript is the fact that
Equality by value does not exist for objects in JavaScript
Finding differences between the virtual DOM and the next DOM that React wants to repaint is impossible because JavaScript has no ability to discern
console.log([] === [])
My example doesn't explain the weakness of manually mutating state. It's this one.
this.state = {}
this.state.arr = []
const prevArr = this.state.arr
this.state.arr.push(10)
console.log(this.state.arr === prevArr)
An array of [10] with a new value is registered as equal to [] because equality is done by reference, and adding a value to an existing element is still equal to its previous state. Here is how to fix it. It is no coincidence that you do this in React as well
this.state = {}
this.state.arr = []
const prevArr = [...this.state.arr]
prevArr.push(10)
this.state.arr
console.log(this.state.arr === prevArr)
Making a new copy of the array retains all the pointers to the values, but it is its own distinct entity in your hardware's memory. Now they are different. When React traverses its virtual DOM, it now has the ability to register that you inserted 10 into your array and want that to be reflected in the next iteration of the DOM.
this.setState triggers a rerender
A rerender is not a complete repainting of the DOM. It is triggering a repaint of the particular element you're passing in when it finds a difference.
I'm struggling with some updates on my Component. I know I shouldn't set props inside the states. However, I had to do this to make my component update properly:
componentWillReceiveProps(nextProps) {
this.setState({
doctor: nextProps.data.name,
address: nextProps.data.address
})
}
Is there a better way to do that? Is a best approach if I do this ->
componentWillReceiveProps(nextProps) {
this.props.data.name = nextProps.data.name;
this.props.data.name = nextProps.data.address;
})
}
I was trying to use the shouldComponentUpdate:
shouldComponentUpdate: function(nextProps, nextState) {
return nextProps.id !== this.props.id;
}
but I didn't work quite well for me.c
In your comment, you mention:
when I come back to the ListView the item I unfavourited still there
and another item disappeared
This looks like a problem in a completely different area. My guess would be that you are using the wrong key in a list. Probably an index. Keys should always be unique to the item you are displaying, and index is not (e.g. the first item is always index 0, and when you rearrange the list, or delete the first item, another item will have index 0, and react does not work well then.) Further explanation here.
About "updating the component properly":
If you pass in new props, react automatically re-renders with the new props. You do not need to do anything in componentWillReceiveProps for this.
componentWillReceiveProps is for updating state, based on comparing OLD and NEW props. (e.g. if you want to display whether number of likes in a prop has gone up or down)
shouldComponentUpdate is optional. Main purpose is to increase performance without any functional change to the workings of your component: to tell react early on that the component is unchanged. I would advise not to include shouldComponentUpdate as long as your component does not yet work as intended.
A wild guess here. As I perceive it, you experience issues properly implementing shouldComponentUpdate. I believe you try comparing nextProps.data objects and always have not equal result, even though the data within is equal. The reason for it is that the object references to data objects are different. In order to overcome that issue, you should be doing a deep comparison, similar to lodash's _.isEqual instead.
As mentioned in comments, updating nextProps in componentWillReceiveProps is a horrendous idea.
I am looking for a best practice to have a ReactJS component responsible for the form for users to edit a given entity. Very simplified example here. Actual forms would in many cases have several more fields and more GUI functionality.
React.createClass({
getInitialState: function() {
return {
entity: {
property1: null,
property2: null
}
};
},
handleChange: function(e) {
var entity = this.state.entity;
switch(e.target.name) {
case 'property1':
entity.property1 = e.target.value;
break;
case 'property2':
entity.property2 = e.target.value;
break;
}
this.setState({
entity: entity
});
},
render: function() {
return (
<div className="entity-form">
<form onChange={this.handleChange}>
<input type="text" name="property1" value={this.state.entity.property1} />
<br />
<textarea name="property2" value={this.state.entity.property2}></textarea>
<br />
</form>
</div>
);
}
});
The fields of the form is directly editing an entity object, that could then be saved to a RESTful api. I want the component to be updated as the user change the fields, so the GUI could react based on the input during typing (like validations, info etc).
In theory, I could have the whole state object represent the entity that is being edited, so every property of the entity is first level state variables. However, I want to be able to add additional state variables for GUI functions and other things related to what the component is going to do, so I would prefer the entity object to be one state variable like the "entity" state variable above. The object could of course be some more complicated object, like a Backbone model or similar, but in this simplified example, I just use a simple object whit the required properties.
So, in search of the best practice way to make React components for this purpose, I have some questions:
Props or state.
In this case, I have chosen to put the entity object with the content for the form in a state variable instead of prop. This is to be able to update the object during form input without having to call the parent and update the props. As far as my React experience goes, that would be the best practice for a form component like this.
Controlled or uncontrolled inputs.
In the simplified example above, I use controlled inputs. This leads to updating the state and re-rendering the component on every change (like every character entered of a text field). Is this the best practice? The good thing is that the component has full control of what happens, instead of having defaultValue paramters, and on some event (like the user pressing a save button), the component extract the values, update the entity and save it to the server. Is there any reasons (or opinions) on if controlled or uncontrolled inputs should be used in cases like this?
onChange for the form or every input
The example has an onChange on the form tag, and it causes the handleChange method to be called every time any of the fields in the form is changed. However, since the inputs are controlled (have value parameters), React complains that the input fields does not have an onChange property. Does this mean having a common onChange on the form tag is bad practice, and I should remove it and put onChange on every single field instead?
Updating individual properties
In the above example, I use a switch based on what input field is being update (when handleChange is called). I guess I could instead make sure all field names is in sync with the property names of the entity, and I can set properties of the entity object in handleChange based on the name of the field from the event (e.target.name). However, this makes it hard to have individual needs per field, even if most fields just update an entity property directly. I guess an alternativ is a switch with a default block setting based on the name of the input, and case blocks for any field that require other ways of updating (like filtering the value before setting it on the entity). Please comment this if you know some much better way of handeling field updates this way.
Updating the state entity
One big problem of this example, is the way the entity object is updated. Since the entity variable in the handleChange is set to the entity object from current state, this is just a pointer, and updating the entity variable will change the object in state. The React pages say you should never update state directly. One of the reasons is something I have experienced when updating the state this way before calling setState. If having a shouldComponentUpdate method, the prevState contain the new state, since the content of the prevState argument sent to the shouldComponentUpdate is based on what was in the state when setState was called. As far as I know, there is no simple way to clone a object in javascript. So the question is, when having whole objects that I need to update properties of (and not touching the other values in the object) instead of just running setState of a single state variable, what is the best way to do this without causing theese kinds of state mixups?
Anything that is going to change goes in State.
If you're looking at loading an existing entity and editing it, you want controlled inputs, and you want to set the values accordingly. I tend to stay away from defaultValue in most cases (outside of dropdowns)
This ties back in to your previous question. If you specify a value, you are using a controlled input, and you have to provide an onChange handler for any controlled input, otherwise it is set in stone. A benefit of controlled inputs is that users can't edit them, so if you had some properties locked down (maybe for read only, security reasons), when the user attempts to save, even if they edited the HTML directly, React should pull the property's value from the vDOM representation (could be wrong here, but I believe I've tested this before). Anyway, you have to have onChange set directly on controlled inputs. As far as using event delgation (at the form level), this isn't a bad practice at all for a lot of events, this is just a specific scenario (controlled inputs) where you need onChange events specified for each element.
Not entirely sure what the ask on this one is, but I used refs instead of target.name.
So, you're correct in that you should never alter the state directly, and this is a tricky bit from the docs. React is going to alter state directly, it's just going to do it in the implementation through setState. If you alter state outside of this method call, unexpected things will happen and errors will be thrown.
shouldComponentUpdate only does shallow comparisons, but there are a few solutions here.
One is to stringify the objects, this is a quick and dirty object comparison, don't really recommend it, but it works.
A better solution, and one I have used with React + Flux is to implement a propertyChanged bool, and just check that in your shouldComponentUpdate.
Now, this will require you to be aware of setting it when things change, i.e., you changed something deeper in the object graph. Say propertyOne is an object with a property that gets changed in your handleChange method. You would validate the input however you wish, then set propertyChanged = true, and you then need to implement componentDidUpdate. We're making an assumption here, but if the component has updated, you set propertyChanged back to false so you don't have any further triggering of unwanted updates. I hope that makes sense. It's kinda like a one-way notifyPropertyChanged.
I'm providing a quick example of what I would probably do for a more dynamic implementation that allows you to add more properties to your object (only shallow properties in this implementation, obviously you could write a more robust solution). Let me know if you have any further questions or if I didn't answer something.
http://jsfiddle.net/rpv9trhh/
var e = {
prop1: 'test',
prop2: 'wee',
prop3: 'another property',
propFour: 'Oh yeah!'
};
var FormComp = React.createClass({
getInitialState: function(){
return {
entity: this.props.entity
}
},
render: function() {
var ent = this.state.entity;
var that = this;
var inputs = [];
for(var key in ent){
inputs.push(<input
key={key}
style={{display:'block'}}
type="text"
ref={key} onChange={that._propertyChanged.bind(null, key)}
value={ent[key]} />)
}
return <form>
{inputs}
<input
type="button"
onClick={this._saveChanges}
value="Save Changes" />
</form>;
},
_propertyChanged: function(propName) {
var nextProp = this.refs[propName].getDOMNode().value;
var nextEntity = this.state.entity;
nextEntity[propName] = nextProp;
this.setState({
entity: nextEntity
});
},
_saveChanges: function() {
var updatedEntity = this.state.entity;
for(var key in updatedEntity){
alert(updatedEntity[key]);
}
//TODO: Call to service to save the entity, i.e.
ActionCreators.saveEntity(updatedEntity);
}
});
React.renderComponent(<FormComp entity={e} />, document.body);