Skip to content

Instantly share code, notes, and snippets.

@lostpebble
Created January 21, 2020 10:47
Show Gist options
  • Save lostpebble/03340b2ecfede16ed96f2763c385a332 to your computer and use it in GitHub Desktop.
Save lostpebble/03340b2ecfede16ed96f2763c385a332 to your computer and use it in GitHub Desktop.
import React, { createContext, useCallback, useContext, useEffect, useRef } from "react";
import { useFela } from "react-fela";
interface IFelaCache { cache: { [key: string]: string }; set: TSetCacheValue; };
type TSetCacheValue = (key: string, classes: string) => string;
const felaCacheContext = createContext<IFelaCache>({ cache: {}, set: (key, classes) => ""});
const Provider = felaCacheContext.Provider;
export const FelaCacheProvider: React.FC<{ changeOrd: number, enabled?: boolean; }> = ({ children, changeOrd, enabled = true }) => {
const cache = useRef<IFelaCache>();
const prevChangeOrd = useRef<number>(-1);
const setCacheValue = useCallback<TSetCacheValue>((key: string, classes: string) => {
if (enabled) {
cache.current!.cache[key] = classes;
}
return classes;
}, [enabled]);
if (changeOrd !== prevChangeOrd.current || cache.current === undefined) {
cache.current = { cache: {}, set: setCacheValue };
prevChangeOrd.current = changeOrd
}
return <Provider value={cache.current}>{children}</Provider>
};
export function useFelaClasses(rule: any, props: any, key: string): string {
const { renderer } = useFela();
const cacheContext: IFelaCache = useContext(felaCacheContext);
let classes = cacheContext.cache[key];
if (classes) {
return classes;
}
return cacheContext.set(key, renderer.renderRule(rule, props));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment