Equivalent to componentDidUpdate using React hooks

The useRef creates an “instance variable” in functional component. It acts as a flag to indicate whether it is in mount or update phase without updating state.

const mounted = useRef();
useEffect(() => {
  if (!mounted.current) {
    // do componentDidMount logic
    mounted.current = true;
  } else {
    // do componentDidUpdate logic
  }
});

Leave a Comment