Wrapping useContext in custom hook and HOC adapter

Aman - Jan 10 '23 - - Dev Community

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
. . .
Terabox Video Player