# [React Hook](https://reactjs.org/docs/hooks-intro.html) for showing custom "Add to homescreen" prompt **Demo:**
[Twitter](https://twitter.com/rikurouvila/status/1067720501634654208) Simple React Hook for showing the user a custom "Add to homescreen" prompt. ```js const [prompt, promptToInstall] = useAddToHomescreenPrompt(); ``` Listens for `beforeinstallprompt` event, which notifies you when the browser would have shown the default dialog, intercepts it and lets you take over and show the prompt when ever you please. ### Browser support and requirements [Add to Home Screen](https://developers.google.com/web/fundamentals/app-install-banners/) Browser support is still quite lacking. At the time of writing, only Chrome (Desktop + Android) [is supported](https://caniuse.com/#feat=web-app-manifest). ### Implementation ```js import * as React from "react"; interface IBeforeInstallPromptEvent extends Event { readonly platforms: string[]; readonly userChoice: Promise<{ outcome: "accepted" | "dismissed"; platform: string; }>; prompt(): Promise; } export function useAddToHomescreenPrompt(): [ IBeforeInstallPromptEvent | null, () => void ] { const [prompt, setState] = React.useState( null ); const promptToInstall = () => { if (prompt) { return prompt.prompt(); } return Promise.reject( new Error( 'Tried installing before browser sent "beforeinstallprompt" event' ) ); }; React.useEffect(() => { const ready = (e: IBeforeInstallPromptEvent) => { e.preventDefault(); setState(e); }; window.addEventListener("beforeinstallprompt", ready as any); return () => { window.removeEventListener("beforeinstallprompt", ready as any); }; }, []); return [prompt, promptToInstall]; } ``` ### Example component ```js import * as React from "react"; import { useAddToHomescreenPrompt } from "./useAddToHomescreenPrompt"; export function ExampleComponent() { const [prompt, promptToInstall] = useAddToHomescreenPrompt(); const [isVisible, setVisibleState] = React.useState(false); const hide = () => setVisibleState(false); React.useEffect( () => { if (prompt) { setVisibleState(true); } }, [prompt] ); if (!isVisible) { return
; } return (
Hello! Wanna add to homescreen?
); } ```