Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
withContext HOC providing Contexts
// usage example
const ChildComponent = ({ CanvasContext }) => {
const { setCanvasEl } = useContext(CanvasContext);
return <canvas ref={setCanvasEl} />;
}
const Component = ({ CanvasContext }) => {
const {canvasEl } = useContext(CanvasContext);
const contexts = { CanvasContext };
// .. do something with canvasEl
return (
<div>
<ChildComponent {...contexts} />
</div>
)
}
withContext({
stateName: 'canvasEl',
setStateName: 'setCanvasEl',
contextName: 'CanvasContext',
})(Component)
import React, { createContext, useState } from 'react';
/* For easy Nested State, intent is not for app wide state but for component shared state */
const withContext = ({
stateName,
setStateName,
stateHook = useState,
defaultState,
contextName,
}) => (BaseComponent) => {
const Context = createContext(defaultState);
const WithContextProvider = ({ children }) => {
const [state, stateSetterFn, ...otherHookReturns] = stateHook(defaultState);
return (
<Context.Provider
// maybe return array here like hooks
value={{
[stateName]: state,
[setStateName]: stateSetterFn,
otherHookReturns,
}}
>
{children}
</Context.Provider>
);
};
const WithContext = (props) => (
<WithContextProvider>
<BaseComponent {...{ ...props, [contextName]: Context }} />
</WithContextProvider>
);
WithContext.defaultProps = {};
return WithContext;
};
export default withContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.