How to get latest props in componentWillUnmount?

30 Views Asked by At

I have a below parent component where I am updating id value to 2 which is a state of parent component and I am rendering the Child component only if id value equals to 1, if I do so Child component will definitely get unmounted.

In Unmount method I need the updated props that is id equals to 2

import React, { useState } from 'react';
import Child from './Child.jsx'
export function App(props) {
  const [id, setId] = useState(1);
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      {
        id === 1 && <Child id={id} />
      }
      <button onClick={() => setId(2)}>change value</button>
    </div>
  );
}

// Log to console
console.log('Hello console')

and a child component like below

import React from 'react';

export default class Child extends React.Component {
  constructor(props){
    super(props);
    this.state = {

    }
  }
  componentDidUpdate() {
    console.log('componentDidMount', this.props.id);
  }

  componentWillUnmount() {
    console.log('this.props', this.props.id);
  }

  render() {
    return (
      <div>
        Child
      </div>
    )
  }

}
1

There are 1 best solutions below

0
Hadi El Yakhni On

id = 2 will never be passed to the child component, since as you said, when it's 2, the child will be unmounted. Hence, it can not be read from your Child's componentWillUnmount

If you're willing to change your architecture a bit, maybe don't unmount the child, edit your code to be something like:

import React, { useState } from 'react';
import Child from './Child.jsx'
export function App(props) {
  const [id, setId] = useState(1);
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <Child id={id} />  {/* always render the child */}
      <button onClick={() => setId(2)}>change value</button>
    </div>
  );
}

export default class Child extends React.Component {
  constructor(props){
    super(props);
    this.state = {

    }
  }

  componentDidUpdate() {
    console.log('componentDidMount', this.props.id);
  
    if(this.props.id == 2) {
      // do something here
    }
  }

  render() {
    if(this.props.id == 2) return null; 

    return (
      <div>
        Child
      </div>
    )
  }
|

I am not sure if this will suit your use case.