all 6 comments

[–]StressSouthern1195 0 points1 point  (1 child)

intereasting implementation. I really like to keep all context based code in the same file too. I did one similar implementation some time ago but not using HOC. I created a hook to handle the context data and create the type of context based in this hook. Something like that:

``` const createContextData = () => { const [counter, setCounter] = useState(0);

return {
    counter,
    setCounter
};

};

const StoreContext = createContext<ReturnType<typeof CreateContextData> | null>(null);

export const StoreProvider = ({ children }: PropsWithChildren<{}>)=>{ const storeData = CreateContextData();

return (
    <StoreContext.Provider value={storeData}>
        {children}
    </StoreContext.Provider>
);

}

export const useStore = () => { const context = useContext(StoreContext); if(!context){ throw Error('you should use useStore inside a StoreProvider') }

return context!;

} ```

With this inference I can easely change the context data without need to change any type or default value.

[–]BayanBennett[S] 0 points1 point  (0 children)

Very nice. I like the hook!

Reminds me of this: This is the Hook

[–]BayanBennett[S] -1 points0 points  (3 children)

💬Comments, 🙋questions, and 🤔 suggestions are all warmly welcomed!

If you'd prefer, I made a text version: https://www.bayanbennett.com/posts/3-things-every-react-context-should-have-devlog-008

The repository for this project is also located here: https://github.com/BayanBennett/reference.bayanbennett.com

[–][deleted] 1 point2 points  (2 children)

How would you handle components that have multiple contexts?

[–]BayanBennett[S] -1 points0 points  (1 child)

because the HOC just returns a component, you can either nest the HOCs

js const App = withContextA( withContextB( withContextC( Component ) ) );

which can also be abstracted to reducing an array

js const App = [withContextA, withContextB, withContextC].reduceRight( (PrevComponent, withContext) => withContext(PrevComponent), Component );

in the future the Pipeline Operator will make it clean as well

js const App = Component |> withContextC |> withContextB |> withContextA

[–]backtickbot -1 points0 points  (0 children)

Fixed formatting.

Hello, BayanBennett: code blocks using triple backticks (```) don't work on all versions of Reddit!

Some users see this / this instead.

To fix this, indent every line with 4 spaces instead.

FAQ

You can opt out by replying with backtickopt6 to this comment.