DEV Community

Cover image for How To Render a React Component Only Once
Rodion Chachura
Rodion Chachura

Posted on • Originally published at radzion.com

How To Render a React Component Only Once

🐙 GitHub | 🎮 Demo

There are situations when we want to display information to the user just once. Usually, it would be for marketing or educational purposes. For example, Increaser shows a link to a YouTube video explaining the concepts behind the feature. We wouldn't want to keep this link constant since we prefer an uncluttered interface. For such purposes, we can use the ShowOnce component.

It takes two properties - children to display and a storage key. To know if the component has been rendered before we rely on the persistent storage that serves as a wrapper around local storage, you can learn more about the implementation here. On the ShowOnce component unmount we'll write in the storage the timestamp, and, therefore, on the next mount wasShownAt will be defined, and we won't render anything.

import { ComponentWithChildrenProps } from "lib/shared/props"
import { useEffect } from "react"
import {
  PersistentStorageKey,
  usePersistentStorageValue,
} from "state/persistentStorage"

interface ShowOnceProps extends ComponentWithChildrenProps {
  storageKey: PersistentStorageKey
}

export const ShowOnce = ({ children, storageKey }: ShowOnceProps) => {
  const [wasShownAt, setShowTime] = usePersistentStorageValue<
    number | undefined
  >(storageKey, undefined)

  useEffect(() => {
    return () => {
      setShowTime(Date.now())
    }
  }, [setShowTime])

  return wasShownAt ? null : <>{children}</>
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)