Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Icon Caching component
import * as React from 'react'
import hash from 'fnv1a'
export const IconCache = React.createContext({})
IconCache.displayName = 'IconCache'
export const useIconCache = () => React.useContext(IconCache)
const withIcon = (icon) => {
const Icon = (props) => {
const { size = 24, color = 'currentColor', ...propsWeDontControl } = props
const cache = useIconCache()
const cachedId = cache[icon]
let id
if (!cachedId) {
id = `icon-${hash(icon).toString(16)}`
cache[icon] = id
}
return (
<svg
{...propsWeDontControl}
viewBox="0 0 24 24"
width={size}
height={size}
fill="currentColor"
style={{ color }}
dangerouslySetInnerHTML={{
__html: cachedId
? `<use href="#${cachedId}" />`
: `<g id="${id}">${icon}</g>`,
}}
/>
)
}
return React.memo(Icon)
}
export default withIcon
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment