loading...
Cover image for Use React Context as a Custom Hook

Use React Context as a Custom Hook

alexandprivate profile image Alex Suarez ・2 min read

Photo by Negative Space, at Pexels

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}

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 ( ... )
 }

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>
 }

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 ( ... )
 }

Final thoughts

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

Posted on Mar 11 by:

alexandprivate profile

Alex Suarez

@alexandprivate

Former Physician, Sr. Frontend Engineer / UI Designer, coding for the last 10 years. Engineer II at @everymundo

Discussion

markdown guide