Created
March 6, 2021 07:31
-
-
Save brandonpittman/e1e5ce1f9524c0102458a87531004041 to your computer and use it in GitHub Desktop.
Icon Caching component
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 * 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