The render method

We should always keep in mind that setting the state causes the component to re-render and, for that reason, we should only store in the state those values that we are using inside the render method.

For example, if we need to persist API subscriptions or timeout variables that we use inside our components, but that do not affect the render in any way, we should consider keeping them in a separate module.

The following code is wrong, because we are storing a value in the state to use it later, but we do not access it in our render method, and we fire an unnecessary render when we set the new state:

  componentDidMount() { 
this.setState({
request: API.get(...);
});
}

componentWillUnmount() {
this.state.request.abort();
}

In a scenario like the previous one, it would be preferable to keep the API request stored in an external module.

Another common solution for this kind of situation is to store the request as a private member of the component instance:

  componentDidMount() { 
this.request = API.get(...);
}

componentWillUnmount() {
this.request.abort();
}

In that way, the request is encapsulated into the component without affecting the state, so it does not trigger any additional rendering when the value changes.

The following cheat sheet from Dan Abramov will help you make the right decision:

  function shouldIKeepSomethingInReactState() {
if (canICalculateItFromProps()) {
// Don't duplicate data from props in state
// Calculate what you can in render() method
return false;
}

if (!amIUsingItInRenderMethod()) {
// Don't keep something in the state
// if you don't use it for rendering.
// For example, API subscriptions are
// better off as custom private fields
// or variables in external modules.
return false;
}

// You can use React state for this!
return true;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset