useMounted React hook

Updated 2 months ago - 1 min read

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";