How to do React forceUpdate() to a child component?

Viewed 4885

I can force reload for a parent component with this.forceUpdate(), but how to do it for a child component?

i.e. following react class methods:

buttonClick = () => {
   //This updates parent (this) component
   this.forceUpdate(); 

  //This causes runtime error ("..not a function in buttonClick...")
   Rtable.forceUpdate();
}

render () {
  <div>
     <RTable />
  </div>
}
2 Answers

If child component is not memoized then rendering its parent will render the child.

If child component is memoized, you could force update with its reference.

And of course, passing different properties to a child, changing its state, will re-render it.

Changing the key will UNMOUNT the component, it is like making a conditional rendering on it.

Here is an example demonstating everything mentioned:

class Child extends React.Component {
  componentDidMount() {
    console.log("mounted");
  }
  render() {
    console.log("rendered");
    return <div>Child</div>;
  }
}

class App extends React.Component {
  state = {
    counter: 0
  };

  childRef = React.createRef();
  onClick = () => this.forceUpdate();
  onCounter = () => this.setState({ counter: this.state.counter + 1 });
  onRef = () => this.childRef.current.forceUpdate();

  render() {
    return (
      <>
        <Child key={this.state.counter} ref={this.childRef} />
        <button onClick={this.onClick}>Render</button>
        <button onClick={this.onCounter}>Update Key</button>
        <button onClick={this.onRef}>Render with ref</button>
      </>
    );
  }
}

Edit lucid-hill-vfvr3

<RTable key={some variable that changes between renders} />

As pointed out below this will cause unmount, which causes the child to lose its state and also run componentWillUnmount, componentDidMount and constructor methods (which may be useful when you want to resubscribe).

Documentation https://reactjs.org/docs/glossary.html#keys

Related