Skip to content

Instantly share code, notes, and snippets.

@wmertens
Created July 22, 2019 22:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmertens/d481257e6950d5c2c6a0324f15806386 to your computer and use it in GitHub Desktop.
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
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)
}
@wmertens
Copy link
Author

available as the react-use-id-hook npm package

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment