Created
August 16, 2021 08:12
-
-
Save fostyfost/a22c8f1aa0b66e66984be722ff209ccb to your computer and use it in GitHub Desktop.
React isomorphic `useLayoutEffect` hook with `react-hooks` linter support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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