How to reduce updates in react

Asked
Active3 hr before
Viewed126 times

10 Answers

react
90%

Internally, React uses several clever techniques to minimize the number of costly DOM operations required to update the UI. For many applications, using React will lead to a fast user interface without doing much work to specifically optimize for performance. Nevertheless, there are several ways you can speed up your React application.,The last interesting case is C8. React had to render this component, but since the React elements it returned were equal to the previously rendered ones, it didn’t have to update the DOM.,When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM.

npm run build
load more v
88%

Just could do something like below. Not 100% sure it'll work as you need. But just try it. Will have to call textBoxLostFocus() when typing is finished (when loosing focus of the textbox),What way is there to stop a parent updating a child, or keeping focus so I can keep typing when the node is updated? , Why does light accelerate instantaneously to c, while no other phenomena do it?

Just could do something like below. Not 100% sure it'll work as you need. But just try it. Will have to call textBoxLostFocus() when typing is finished (when loosing focus of the textbox)

constructor() {
   super()
   this.state = {
      diagramUpdateFlag: false
   }
}

shouldComponentUpdate(nextProps, nextState) {
   if (this.state.diagramUpdateFlag === nextState.diagramUpdateFlag) {
      return false
   } else {
      return true
   }
}

textBoxLostFocus() {
   this.setState({
      diagramUpdateFlag: !this.state.diagramUpdateFlag
   })
}
72%

Here's how it works: You pass a function to setState() that takes state and props as parameters and returns your desired state, which React will then use for the update. We go from this:,This means you can decouple the state update logic from your components and export it to a new file to make it reusable and declarative. Sweet!,Well, you can now prevent state updates and re-renders straight from setState(). You just need to have your function return null. For example, there is a maximum number of pizzas I can eat before I pass out. We don't want to continue updating and re-rendering after that point. There are many ways you can prevent that in React, but here's how you do it with functional setState():

Here's how it works: You pass a function to setState() that takes state and props as parameters and returns your desired state, which React will then use for the update. We go from this:

// Increase the numbers of pizzas I need to eat
this.setState({
   pizzas: this.state.pizzas + 1
});
load more v
65%

Note: If updating/changing your email, a validation request will be sent,Tree shaking is the process of removing unused or dead code from the bundles. This is especially important when using utility libraries like Lodash where you do not need all features of the imported library., Is your profile up-to-date? Please take a moment to review and update.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

As you can see, the shouldComponentUpdate class method has access to the next props and state before running the re-rendering of a component. That's where you can decide to prevent the re-render by returning false from this method. If you return true, the component re-renders.,You can use a class component with a componentShouldUpdate method:,The first solution used to prevent a component from rendering in React is called shouldComponentUpdate. It is a lifecycle method which is available on React class components. Instead of having Square as a functional stateless component as before:

Before learning about React's API for perf optimizations, let's come up with a scenario that enables us to apply React's shouldComponentUpdate and PureComponent. In the following, you will be rendering a large list of items. After experiencing the rerendering of the list of items as performance problem, we will go through different performance optimization solutions. Your initial application will be the following:

import React, { Component } from 'react';import styled from 'styled-components'; const list = new Array(5000).fill(0).map((v, i) => i); class App extends Component {  render() {    return (      <div>        {list.map(v => <Square key={v} number={v} />)}      </div>    );  }} const Square = ({ number }) => <Item>{number * number}</Item>; const Item = styled.div`  margin: 10px;`; export default App;
import React, { Component } from 'react';import styled from 'styled-components'; const list = new Array(5000).fill(0).map((v, i) => i); class App extends Component {  render() {    return (      <div>        {list.map(v => <Square key={v} number={v} />)}      </div>    );  }} const Square = ({ number }) => <Item>{number * number}</Item>; const Item = styled.div`  margin: 10px;`; export default App;

In the next step, let's add an interactive element to our application. Next to the list of squares, there should be a button to toggle the perspective of the list.

import React, { Component } from 'react';import styled from 'styled-components'; const list = new Array(5000).fill(0).map((v, i) => i); class App extends Component {  state = {    perspective: false,  };   togglePerspective = () => {    this.setState(state => ({ perspective: !state.perspective }));  };   render() {    return (      <div>        <Button onClick={this.togglePerspective}>          Toggle Perspective        </Button>         <div>          {list.map(v => <Square key={v} number={v} />)}        </div>      </div>    );  }} const Button = ({ onClick, children }) => (  <button type="button" onClick={onClick}>    {children}  </button>); const Square = ({ number }) => <Item>{number * number}</Item>; const Item = styled.div`  margin: 10px;`; export default App;
import React, { Component } from 'react';import styled from 'styled-components'; const list = new Array(5000).fill(0).map((v, i) => i); class App extends Component {  state = {    perspective: false,  };   togglePerspective = () => {    this.setState(state => ({ perspective: !state.perspective }));  };   render() {    return (      <div>        <Button onClick={this.togglePerspective}>          Toggle Perspective        </Button>         <div>          {list.map(v => <Square key={v} number={v} />)}        </div>      </div>    );  }} const Button = ({ onClick, children }) => (  <button type="button" onClick={onClick}>    {children}  </button>); const Square = ({ number }) => <Item>{number * number}</Item>; const Item = styled.div`  margin: 10px;`; export default App;

The local state of the App component changes when the button is clicked, but the local state itself isn't used yet. In the last step, you are using a styled component with a conditional to toggle the perspective by applying a flexbox style.

import React, { Component } from 'react';import styled from 'styled-components'; const list = new Array(5000).fill(0).map((v, i) => i); class App extends Component {  state = {    perspective: false,  };   togglePerspective = () => {    this.setState(state => ({ perspective: !state.perspective }));  };   render() {    return (      <div>        <Button onClick={this.togglePerspective}>          Toggle Perspective        </Button>         <Perspective perspective={this.state.perspective}>          {list.map(v => <Square key={v} number={v} />)}        </Perspective>      </div>    );  }} const Perspective = styled.div`  display: flex;  flex-wrap: wrap;  flex-direction: ${props => (props.perspective ? 'row' : 'column')};`; const Button = ({ onClick, children }) => (  <button type="button" onClick={onClick}>    {children}  </button>); const Square = ({ number }) => <Item>{number * number}</Item>; const Item = styled.div`  margin: 10px;`; export default App;
import React, { Component } from 'react';import styled from 'styled-components'; const list = new Array(5000).fill(0).map((v, i) => i); class App extends Component {  state = {    perspective: false,  };   togglePerspective = () => {    this.setState(state => ({ perspective: !state.perspective }));  };   render() {    return (      <div>        <Button onClick={this.togglePerspective}>          Toggle Perspective        </Button>         <Perspective perspective={this.state.perspective}>          {list.map(v => <Square key={v} number={v} />)}        </Perspective>      </div>    );  }} const Perspective = styled.div`  display: flex;  flex-wrap: wrap;  flex-direction: ${props => (props.perspective ? 'row' : 'column')};`; const Button = ({ onClick, children }) => (  <button type="button" onClick={onClick}>    {children}  </button>); const Square = ({ number }) => <Item>{number * number}</Item>; const Item = styled.div`  margin: 10px;`; export default App;

Now you should be able to toggle the perspective (rows, columns) of the list of items by clicking the button. Depending on the number of items you are generating for your list once your application starts, the toggling of the perspective takes some time, because with every state change all your components rerender. You can confirm it by adding console logs to your App component's child components and the App component itself.

... class App extends Component {  state = {    perspective: false,  };   togglePerspective = () => {    this.setState(state => ({ perspective: !state.perspective }));  };   render() {    console.log('render App');    return (      <div>        <Button onClick={this.togglePerspective}>          Toggle Perspective        </Button>         <Perspective perspective={this.state.perspective}>          {list.map(v => <Square key={v} number={v} />)}        </Perspective>      </div>    );  }} const Button = ({ onClick, children }) =>  console.log('render Button') || (    <button type="button" onClick={onClick}>      {children}    </button>  ); const Square = ({ number }) =>  console.log('render Square') || <Item>{number * number}</Item>; ...
... class App extends Component {  state = {    perspective: false,  };   togglePerspective = () => {    this.setState(state => ({ perspective: !state.perspective }));  };   render() {    console.log('render App');    return (      <div>        <Button onClick={this.togglePerspective}>          Toggle Perspective        </Button>         <Perspective perspective={this.state.perspective}>          {list.map(v => <Square key={v} number={v} />)}        </Perspective>      </div>    );  }} const Button = ({ onClick, children }) =>  console.log('render Button') || (    <button type="button" onClick={onClick}>      {children}    </button>  ); const Square = ({ number }) =>  console.log('render Square') || <Item>{number * number}</Item>; ...

The first solution used to prevent a component from rendering in React is called shouldComponentUpdate. It is a lifecycle method which is available on . Instead of having Square as a functional stateless component as before:

const Square = ({ number }) => <Item>{number * number}</Item>;
const Square = ({ number }) => <Item>{number * number}</Item>;

You can use a class component with a componentShouldUpdate method:

class Square extends Component {  shouldComponentUpdate(nextProps, nextState) {    ...  }   render() {    return <Item>{this.props.number * this.props.number}</Item>;  }}
class Square extends Component {  shouldComponentUpdate(nextProps, nextState) {    ...  }   render() {    return <Item>{this.props.number * this.props.number}</Item>;  }}

As you can see, the shouldComponentUpdate class method has access to the next props and state before running the re-rendering of a component. That's where you can decide to prevent the re-render by returning false from this method. If you return true, the component re-renders.

class Square extends Component {  shouldComponentUpdate(nextProps, nextState) {    if (this.props.number === nextProps.number) {      return false;    } else {      return true;    }  }   render() {    return <Item>{this.props.number * this.props.number}</Item>;  }}
class Square extends Component {  shouldComponentUpdate(nextProps, nextState) {    if (this.props.number === nextProps.number) {      return false;    } else {      return true;    }  }   render() {    return <Item>{this.props.number * this.props.number}</Item>;  }}

In the previous case, you have used shouldComponentUpdate to prevent a rerender of the child component. It can be used to prevent component renderings on a fine-grained level: You can apply equality checks for different props and state, but also use it for other kind of checks. However, imagine you are not interested in checking each incoming prop by itself, which can be error prone too, but only in preventing a rerendering when nothing relevant (props, state) has changed for the component. That's where you can use the more broad yet simpler solution for preventing the rerender: React's PureComponent.

import React, { Component, PureComponent } from 'react'; ... class Square extends PureComponent {  render() {    return <Item>{this.props.number * this.props.number}</Item>;  }}
import React, { Component, PureComponent } from 'react'; ... class Square extends PureComponent {  render() {    return <Item>{this.props.number * this.props.number}</Item>;  }}

As alternative, if you want to use a functional stateless component as PureComponent instead, use recompose's pure . You can install recompose on the command line via npm with npm install recompose. Then apply its higher-order component on your initially implemented Square component:

import { pure } from 'recompose'; ... const Square = pure(({ number }) => <Item>{number * number}</Item>);
import { pure } from 'recompose'; ... const Square = pure(({ number }) => <Item>{number * number}</Item>);
load more v
40%

In both hooks and class components, we have several ways to construct and alter the component’s state. We change the state by calling setState or using useState. These changes cause parts of the component to re-render, and possibly to its children.

Pretag
 Pretag team - issue, fix, solve, resolve
22%

And when the App component mounts, it updates the the counter value every 2 seconds.,React functional components do not have lifecycle methods.,All I need to do in the Greeting component is wrap it another function called React.memo().

React.memo(YourComponent);
load more v
60%

Editor’s note: This React Hooks tutorial was last updated in January 2021 to include more React Hooks best practices and examples.,Depending on your use case, you may find useReducer quite testable.,Check out this React useState video tutorial:

Pretag
 Pretag team - issue, fix, solve, resolve
48%

Instant feedback is not the only way that React Native improves developer velocity. Teams can leverage the fast-growing ecosystem of high quality open source packages. Teams can also share business logic between Android, iOS, and the web. This helps them ship updates faster and reduce organizational silos between platform teams.,See the docs for Appearance and useColorScheme for more information.,19 issues were evaluated and closed by the React Native team.

use_react_native!(: path => config[: reactNativePath], # to enable hermes on iOS, change `false`
   to `true`
   and then install pods: hermes_enabled => true)
load more v
23%

Note: if you ever see mentions of self.reduce, this is the old API. The new API is called self.send. The old API's docs are here.,Testing ReasonReact components,In ReasonReact, you'd do something similar:

Here's a complete, working, stateful ReasonReact component. We'll refer to it later on.

/* State declaration */
type state = {
  count: int,
  show: bool,
};

/* Action declaration */
type action =
  | Click
  | Toggle;

/* Component template declaration.
   Needs to be **after** state and action declarations! */
let component = ReasonReact.reducerComponent("Example");

/* greeting and children are props. `children` isn't used, therefore ignored.
   We ignore it by prepending it with an underscore */
let make = (~greeting, _children) => {
  /* spread the other default fields of component here and override a few */
  ...component,

  initialState: () => {count: 0, show: true},

  /* State transitions */
  reducer: (action, state) =>
    switch (action) {
    | Click => ReasonReact.Update({...state, count: state.count + 1})
    | Toggle => ReasonReact.Update({...state, show: !state.show})
    },

  render: self => {
    let message =
      "You've clicked this " ++ string_of_int(self.state.count) ++ " times(s)";
    <div>
      <button onClick=(_event => self.send(Click))>
        (ReasonReact.string(message))
      </button>
      <button onClick=(_event => self.send(Toggle))>
        (ReasonReact.string("Toggle greeting"))
      </button>
      (
        self.state.show
          ? ReasonReact.string(greeting)
          : ReasonReact.null
      )
    </div>;
  },
};
load more v

Other "react-undefined" queries related to "How to reduce updates in react"