DEV Community

Riku Rouvila
Riku Rouvila

Posted on


React Hook for showing custom "Add to home screen" prompt


const [prompt, promptToInstall] = useAddToHomescreenPrompt();
Enter fullscreen mode Exit fullscreen mode

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 whenever you please.

Browser support and requirements

Add to Home Screen

Browser support is still quite lacking. At the time of writing, only Chrome (Desktop + Android) is supported.


import * as React from "react";

interface IBeforeInstallPromptEvent extends Event {
  readonly platforms: string[];
  readonly userChoice: Promise<{
    outcome: "accepted" | "dismissed";
    platform: string;
  prompt(): Promise<void>;

export function useAddToHomescreenPrompt(): [
  IBeforeInstallPromptEvent | null,
  () => void
] {
  const [prompt, setState] = React.useState<IBeforeInstallPromptEvent | 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) => {

    window.addEventListener("beforeinstallprompt", ready as any);

    return () => {
      window.removeEventListener("beforeinstallprompt", ready as any);
  }, []);

  return [prompt, promptToInstall];

Enter fullscreen mode Exit fullscreen mode

Example component

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

    () => {
      if (prompt) {

  if (!isVisible) {
    return <div />;

  return (
    <div onClick={hide}>
      <button onClick={hide}>Close</button>
      Hello! Wanna add to homescreen?
      <button onClick={promptToInstall}>Add to homescreen</button>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

16 Libraries You Should Know as a React Developer

Being a modern React developer is not about knowing just React itself. To stay competitive, it is highly recommended to explore the whole ecosystem. This article contains some of the most useful React component libraries to speed up your developer workflow.