DEV Community

Cover image for Use React Context as a Custom Hook
Alex Suarez
Alex Suarez

Posted on • Updated on

Use React Context as a Custom Hook

This is a pretty fast look at a workaround to combine react context and hooks

React Context

React Context is simply great, its mas have some downfalls (performance related to components unnecessary re-renders), but overall is amazing, let create a simple context to start

 import React from 'react';

 let MyContext;
 let { Provider } = (MyContext = React.createContext())

 function MyProvider({children}) { 
  return <Provider value={{...}}>{children}</Provider>
 }

 export {MyContext, MyProvider}

Enter fullscreen mode Exit fullscreen mode

Now you can import MyProvider at the component or components you want to use these provider values with, and wrap the component with it.

Inside those components, you typically can access those values by importing the context and destructuring the value there.

 import React from 'react'

 import {MyContext} from 'context'

 function component() {
  const {...values} = React.useContext(MyContext)
  return ( ... )
 }
Enter fullscreen mode Exit fullscreen mode

React Hooks to the rescue

Instead of exporting MyContext and later use it with useContext hook, let's create a custom hook inside the context file that returns inside the * React useContext* hook using native react hook MyContext as an argument, just like this, and let's change a little the exporting methods to use naming and default.

 import React from 'react';

 let MyContext;
 let { Provider } = (MyContext = React.createContext())
 // new line custom hook
 export const useMyContext = () => React.useContext(MyContext)

 export default function MyProvider({children}) { 
  return <Provider value={{...}}>{children}</Provider>
 }

Enter fullscreen mode Exit fullscreen mode

Now you can keep using your provider like before (just import it default), but on the component, you can avoid destructuring from useContext(MyContext) and simply do this

 import React from 'react'

 import {useMyContext} from 'context'

 function component() {
  // a more semantic way to do it!!!
  const {...values} = useMyContext()
  return ( ... )
 }
Enter fullscreen mode Exit fullscreen mode

Final thoughts

That's it, I hope this "syntactic sugar" helps you to write a better code on your next project.

Photo by Negative Space, at Pexels

Top comments (2)

Collapse
 
reubengt profile image
Reuben George Thomas

thanks, this is super helpful!!

Collapse
 
alexandprivate profile image
Alex Suarez

You are welcome Reuben!