Skip to content

Instantly share code, notes, and snippets.

@fostyfost
Created August 16, 2021 08:12
Show Gist options
  • Save fostyfost/a22c8f1aa0b66e66984be722ff209ccb to your computer and use it in GitHub Desktop.
Save fostyfost/a22c8f1aa0b66e66984be722ff209ccb to your computer and use it in GitHub Desktop.
React isomorphic `useLayoutEffect` hook with `react-hooks` linter support
import { useEffect, useLayoutEffect } from 'react'
// React currently throws a warning when using useLayoutEffect on the server.
// To get around it, we can conditionally useEffect on the server (no-op) and
// useLayoutEffect in the browser. We need useLayoutEffect to ensure the store
// subscription callback always has the selector from the latest render commit
// available, otherwise a store update may happen between render and the effect,
// which may cause missed updates; we also must ensure the store subscription
// is created synchronously, otherwise a store update may occur before the
// subscription is created and an inconsistent state may be observed
const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect
export { useIsomorphicLayoutEffect as useLayoutEffect }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment