Created
July 22, 2019 22:04
-
-
Save wmertens/d481257e6950d5c2c6a0324f15806386 to your computer and use it in GitHub Desktop.
Hook for consistent auto-incrementing ids between SSR and browser. To use, wrap your app with <IdProvider> and call useId or useGetId
This file contains 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 React, {createContext, useContext, useRef} from 'react' | |
import PropTypes from 'prop-types' | |
const Id = createContext() | |
const useIdGetter = (prefix = 'id') => { | |
const ref = useRef() | |
if (!ref.current) { | |
const me = {id: 0, get: () => `${prefix}-${me.id++}`} | |
ref.current = me | |
} | |
return ref.current.get | |
} | |
export const IdProvider = ({children}) => { | |
const get = useIdGetter() | |
return <Id.Provider value={get}>{children}</Id.Provider> | |
} | |
IdProvider.propTypes = {children: PropTypes.node.isRequired} | |
export const useId = () => { | |
const getter = useContext(Id) | |
const ref = useRef() | |
if (!ref.current) ref.current = getter() | |
return ref.current | |
} | |
export const useGetId = () => { | |
const getter = useContext(Id) | |
const base = useRef() | |
if (!base.current) base.current = getter() | |
return useIdGetter(base.current) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
available as the react-use-id-hook npm package