Skip to content

Instantly share code, notes, and snippets.

@adamdoe
Last active May 23, 2022 04:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamdoe/c2159994ed763d357972d2b0786ab837 to your computer and use it in GitHub Desktop.
Save adamdoe/c2159994ed763d357972d2b0786ab837 to your computer and use it in GitHub Desktop.
ReactContext #React

React Context

example

// MyContext.js
import React from 'react'
const MyContext = createContext()
export default MyContext

// App.js
<MyContext.Provider value={values}>
<App />
</MyContext.Provider>

Properties on context

  • MyContext.Provider
  • MyContext.Consumer

Provider

allows us to declare data that we want available throughout our component tree.

<MyContext.Provider value={values}>
<App />
</MyContext.Provider>

Consumer

Allows any component in the component tree that needs that data to be able to subscribe to it.

<MyContext.Consumer>
 { (data) => return <h1>{data}</h1> }
</MyContext.Consumer>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment