DEV Community

Aman
Aman

Posted on

Wrapping useContext in custom hook and HOC adapter

You have a component and there are lots of nested sub-component. There is need to share the state between the sub component. We create a state in parent component and pass down the state to the nested component.

It is very inconvenient if there is vary few sub-component is using the state and it is nested level down.

Other way to solve this problem is useContext Hook.
wrap the parent component with ContextProvider and now we can use the state anywhere in sub-component.

If you have a lot of Context.The code readability decreases and it gets ugly.

One of the way to make it better is using custom hook and Provider HOC on top of the useContext.

Let's say we have a isAuth state to be shared in sub-component.

Create AuthProvider HOC wrapper and useAuth hook

const AuthContext = React.useContext<boolean>(false);

export type AuthProviderProps = {
   children: JSX.Element | JSX.Element[];
   isAuth: boolean;
}
export const AuthProvider = ({children, isAuth} : AuthProviderProps) => {
   return (<AuthContext.Provider value={isAuth}>
      {children}
   </AuthContext.Provider>);
}

export const useAuth = () => {
   const isAuth = React.useContext(AuthContext);
   return { isAuth };
}
Enter fullscreen mode Exit fullscreen mode

How to use the hook and HOC

Use the AuthProvider HOC in parent component to wrap the child components.


const [isAuth, setIsAuth] = React.useState<boolean>(false);
....
....
return (
   <AuthProvider isAuth={isAuth}>
      ...
      child components
      ...
   </AuthProvider>);
Enter fullscreen mode Exit fullscreen mode

Somewhere in nested child component, use the useAuth hook to access the isAuth state.

const {isAuth} = useAuth();
...
...
return <div> You are {isAuth ? "" : "not"} authenticated</div>
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay