useMounted React hook

April 04, 2021

views

The hook

Check if your component has mounted. This can be useful if you're using server side rendering.

src/hooks/useMounted.ts
import * as React from "react";
 
export function useMounted() {
  const [isMounted, setMounted] = React.useState(false);
 
  React.useEffect(() => {
    setMounted(true);
 
    return () => {
      setMounted(false);
    };
  }, []);
 
  return isMounted;
}

npm/yarn

You can now also use this hook via npm/yarn by installing my npm package:

npm install @casper124578/useful

Later in your project

import { useMounted } from "@casper124578/useful/hooks/useMounted";