On App Load

On App Load

Run a callback only once on app load

Code

snippets/react/use-on-app-load.ts
import { useEffect } from "react";


let didInit = false;


export const useOnAppLoad = (callback: () => void) => {
  useEffect(() => {
    if (!didInit) {
      didInit = true;


      callback();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
};

Examples

snippets/react/use-on-app-load.example.tsx
import { useOnAppLoad } from "./use-on-app-load";


const Page = () => {
  useOnAppLoad(() => {});


  return <main />;
};


export default Page;

Tests

snippets/react/use-on-app-load.test.ts
import { describe } from "bun:test";


describe.todo("useOnAppLoad", () => {});

Sources