how to update react state without re rendering component?

None of the answers work for TypeScript, so I'll add this. One method is to instead use the useRef hook and edit the value directly by accessing the 'current' property. See here:

const [myState, setMyState] = useState<string>("");

becomes

let myState = useRef<string>("");

and you can access it via:

myState.current = "foobar";

So far I'm not seeing any drawbacks. However, if this is to prevent a child component from updating, you should consider using the useMemo hook instead for readability. The useMemo hook is essentially a component that's given an explicit dependency array.


Here's an example of only re-rendering when a particular condition is fulfilled (e.g. finished fetching).

For example, here we only re-render if the value reaches 3.

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends React.Component { 
  state = { 
    value: 0, 
  }

  add = () => {
    this.setState({ value: this.state.value + 1});
  } 

  shouldComponentUpdate(nextProps, nextState) { 
    if (nextState.value !== 3) { 
      return false;
    }
    return true;
  }

  render() { 
    return (
      <React.Fragment>
        <p>Value is: {this.state.value}</p>
        <button onClick={this.add}>add</button>
      </React.Fragment>
    )
  }
}

render(<App />, document.getElementById('root'));

Live example here.


All data types

useState returns a pair - an array with two elements. The first element is the current value and the second is a function that allows us to update it. If we update the current value, then no rendering is called. If we use a function, then the rendering is called.

const stateVariable = React.useState("value");

stateVariable[0]="newValue"; //update without rendering
stateVariable[1]("newValue");//update with rendering

Object

If a state variable is declared as an object, then we can change its first element. In this case, rendering is not called.

const [myVariable, setMyVariable] = React.useState({ key1: "value" });

myVariable.key1 = "newValue"; //update without rendering
setMyVariable({ key1:"newValue"}); //update with rendering

Array

If a state variable is declared as an array, then we can change its first element. In this case, rendering is not called.

const [myVariable, setMyVariable] = React.useState(["value"]);

myVariable[0] = "newValue"; //update without rendering
setMyVariable(["newValue"]); //update with rendering

Tags:

Reactjs