I am trying to convert a HOC to a hook. My current HOC basically consumes a context, and pass the data as props to the wrapped component. Just like this:
import React from "react";
import BadgesCountersContext from "../../../contexts";
const withBadgesCounters = (Component) => (props) => {
return (
<ContentsContext.Consumer>
{(badgesCounters) => <Component {...props} badgesCounters={badgesCounters} />}
</ContentsContext.Consumer>
);
};
export default withBadgesCounters;
I am using it in components, like this:
const MyComponent = memo((props) => {
...
}, (prevProps, nextProps) => {
return prevProps.badgesCounters["badgeName"] ===
nextProps.badgesCounters["badgeName"];
});
export default withBadgesCounters(MyComponent);
As badgesCounters is a map, which have the following form:
{
badgeName1: 10,
badgeName2: 3,
...
}
I am memoizing the component, to avoid re-renders when other badges that doesn't interest the component changes.
How can I do the same with a hook?
I have just created the following one:
import { useContext } from "react";
import BadgesCountersContext from "../contexts/";
export default function useBadgesCounters() {
const context = useContext(BadgesCountersContext);
if (context === undefined) {
throw new Error("Cannot find BadgesCountersContext");
}
return context;
}
But, it seems that I can't memoize the component as I am not receiving the data as prop.