I'm studying change detection mechanism and I'm having some troubles with reactjs case.
When props are changed in a react component, this component is "rerendered" (not totally true, because of the diff algorithm, but the idea is here) .
I know that when something happens, react browse its internal virtual DOM to check if the new value is the same as the previous one, and rerender as needed its real component tree.
My question is : what is this something.
For example, using angular 2, we have zone.js that allows to catch async stuff (button click, setTimeout etc...) and to trigger change detection.
But for now, I don't know at all of it's triggered with reactjs.
Can you help me ?
Every second the browser calls the tick() method. Inside it, the Clock component schedules a UI update by calling setState() with an object containing the current time. Thanks to the setState() call, React knows the state has changed, and calls the render() method again to learn what should be on the screen.
Considering that the app's state changes, React uses its diffing algorithm (very similar to how Git compares changes in files) to compare the root elements in the virtual DOM and real DOM.
The Diffing Algorithm. When diffing two trees, React first compares the two root elements. The behavior is different depending on the types of the root elements.
How Virtual DOM actually make things faster: When anything new is added to the application, a virtual DOM is created and it is represented as a tree. Each element in the application is a node in this tree. So, whenever there is a change in the state of any element, a new Virtual DOM tree is created.
Try to imagine there are 2 things here:
You need to call this.setState(), this would update the state inside the current component, and subsequently trigger an update (automatically call render()) of this component
This would trigger the props/newProps of this COMPONENT to be updated, and subsequently your component is updated by calling this.setState() inside the component (componentWillReceiveProps is a lifecycle method from React)
class MyComponent extends React.Component {
// initially how the state is set to MyComponent
constructor(props) {
super(props);
this.state = {name: this.props.name};
}
// own method to be called inside MyComponent
updateName(e) {
const newName = e.target.value;
if (this.state.name !== newName) {
this.setState({name:newName});
}
}
// changes from the outside
componentWillReceiveProps(nextProps) {
const newName = nextProps.name;
if (this.state.name !== newName) {
this.setState({name:newName});
}
}
render() {
return(
<div>
{this.state.name}
<input type="text"
onChange={this.updateName.bind(this)}
value={this.state.name} />
</div>
)
}
}
It's worth pointing out that this.setState() would automatically trigger render(), while this.state.name = 'Bob' wouldn't trigger render().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With