Skip to content

Instantly share code, notes, and snippets.

@muddassirm
Last active March 18, 2020 04:52
Show Gist options
  • Save muddassirm/1394cf4f21e229f2d2b59279df365b86 to your computer and use it in GitHub Desktop.
Save muddassirm/1394cf4f21e229f2d2b59279df365b86 to your computer and use it in GitHub Desktop.
Different ways of using React Context API
//Use React Context + Provider/Consumer - Works with both Functional and Class Components
import React from 'react';
const Context = React.createContext();
const ContextApp = () => {
return (
<Context.Provider value={['THE', 'QUICK', 'BROWN', 'FOX', 'JUMPS', 'OVER', 'THE', 'LAZY', 'DOG']}>
<CustomComponent/>
</Context.Provider>
)
}
const CustomComponent = () => {
return (
<Context.Consumer>
{
(items) => {
return <div>{items.map((item) => <li>{item}</li>)}</div>
}
}
</Context.Consumer>
)
}
//Use React Context + Set ContextType - Works only with Class Components
import React from 'react';
const Context = React.createContext();
const ContextApp = () => {
return (
<Context.Provider value={['THE', 'QUICK', 'BROWN', 'FOX', 'JUMPS', 'OVER', 'THE', 'LAZY', 'DOG']}>
<CustomComponent/>
</Context.Provider>
)
}
class CustomComponent extends React.Component {
render(){
let context = this.context
return(<div>{context.map((item) => <li>{item}</li>)}</div>)
}
}
CustomComponent.contextType = Context
//Use React Context + useContext Hook - Works only with Functional Components
import React,{useContext} from 'react';
const Context = React.createContext();
const ContextApp = () => {
return (
<Context.Provider value={['THE', 'QUICK', 'BROWN', 'FOX', 'JUMPS', 'OVER', 'THE', 'LAZY', 'DOG']}>
<CustomComponent/>
</Context.Provider>
)
}
const CustomComponent = () => {
let context = useContext(Context)
return (<div>{context.map((item) => <li>{item}</li>)}</div>)
}
//Use React Context + Access Static ContextType - Works only with Class Components
import React from 'react';
const Context = React.createContext();
const ContextApp = () => {
return (
<Context.Provider value={['THE', 'QUICK', 'BROWN', 'FOX', 'JUMPS', 'OVER', 'THE', 'LAZY', 'DOG']}>
<CustomComponent/>
</Context.Provider>
)
}
class CustomComponent extends React.Component {
static contextType = Context
render(){
let context = this.context
return(<div>{context.map((item) => <li>{item}</li>)}</div>)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment