Skip to content

Instantly share code, notes, and snippets.

@brandonpittman
Created March 6, 2021 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brandonpittman/e1e5ce1f9524c0102458a87531004041 to your computer and use it in GitHub Desktop.
Save brandonpittman/e1e5ce1f9524c0102458a87531004041 to your computer and use it in GitHub Desktop.
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