简体   繁体   中英

Restricting re-renders to specific state change in functional component

If I have a component with three different states and I only want the component to re-render when one specific state in that component changes, how would I go about doing that?

Below I've included a code example. Say I only want this component to re-render when setSecondState() is called, not when setFirstState() or setThirdState() is called.

const ExampleComponent = () => {
     const [firstState, setFirstState] = React.useState(0);
     const [secondState, setSecondState] = React.useState(false);
     const [thirdState, setThirdState] = React.useState("");

     return (
          <div>
                Rendered
          </div>
     );
}

Don't put those in state use ref instead. You can update ref value by updating ref.current, it won't cause re-render.

const ExampleComponent = () => { 

     const firstRef = React.useRef(0);
     const [secondState, setSecondState] = React.useState(false);
     const secondRef = React.useRef("");

     const someFunction = () => {
         firstRef.current = 10;
         secondRef.current = "foo";
     }

     return (
          <div>
                Rendered
          </div>
     );
}

You can use the shouldComponentUpdate lifecycle function. This will return a boolean which tells react to render or not.

In the below example when v1 value changes it does not trigger re-render while changing v2 triggers a re-render.

 class App extends React.Component { state = { v1: 0, v2: 0 } shouldComponentUpdate(nextProps, nextState){ console.log('v1: ', nextState.v1, ', v2: ', nextState.v2); return this.state.v1 === nextState.v1 } render(){ const { v1, v2 } = this.state; return ( <div> <button onClick={() => this.setState(({ v1 }) => ({ v1: v1 + 1 }))}>{`Increase but do not render: ${v1}`}</button><br /> <button onClick={() => this.setState(({ v2 }) => ({ v2: v2 + 1 }))}>{`Increase and render: ${v2}`}</button> </div> ) } } ReactDOM.render(<App />, document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM