Home > Mobile >  logging unmount for JSX element instead of components
logging unmount for JSX element instead of components

Time:12-15

how we can observe if a JSX element mounted or not. for example I have a simple component with useEffect on. it inside of my App.js I can mount and unmount my component and the useEffect inside of that component will log if it is mounted or unmounted. but I wonder if there is way to that with JSX elements. for example , can we implement that for an h2 tag inside of an App.js without creating component ?

App.js

import React, { useState } from "react";
import "./App.css";
import Mycomponent from "./Mycomponent";
const App = () => {
  const [mount, setMount] = useState(true);
  return (
    <div>
      <b>Mounting and Unmounting</b>
      <button
        onClick={() => {
          setMount(!mount);
        }}
      >
        {mount ? "click to unmount" : "click to mount"}
      </button>
      {mount && <Mycomponent />}
    </div>
  );
};

export default App;

Mycomponent.js :

import React, { useEffect } from "react";

const Mycomponent = () => {
  useEffect(() => {
    console.log("mounted");
    return () => {
      console.log("unmounted");
    };
  }, []);
  return (
    <div>
      <h1>component mounted</h1>
    </div>
  );
};

export default Mycomponent;

CodePudding user response:

I think you can use callback refs for that:

export default function App() {
  const [counter, setCounter] = React.useState(0);        

  const measuredRef = (node) => {
    if (node == null) {
      console.log('I was removed');
    } else {
      console.log('I was mounted');
    }
  };

  return (
    <div
      onClick={() => {
        setCounter(counter   1);
      }}
    >
      {counter % 2 == 0 && <h1 ref={measuredRef}>Hello, world</h1>}
      <p>Start editing to see some magic happen :)</p>
    </div>
  );
}

There is a somewhat related example in the docs about that:

In this example, the callback ref will be called only when the component mounts and unmounts, since the rendered <h1> component stays present throughout any rerenders.

  • Related