Skip to content

Instantly share code, notes, and snippets.

@nicolasmendonca
Created October 17, 2020 19:29
Show Gist options
  • Save nicolasmendonca/0d53c35c278da31fce8283647a10469f to your computer and use it in GitHub Desktop.
Save nicolasmendonca/0d53c35c278da31fce8283647a10469f to your computer and use it in GitHub Desktop.
Prevents unnecessary re-renders using a state slice HOC
function withStateSlice(Comp, slice) {
const MemoComp = React.memo(Comp);
function Wrapper(props, ref) {
const state = useAppState();
const cell = slice(state, props);
return <MemoComp ref={ref} state={cell} {...props} />;
}
Wrapper.displayName = `withStateSlice(${Comp.displayName || Comp.name})`;
return React.memo(React.forwardRef(Wrapper));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment