Created
October 3, 2021 10:48
-
-
Save mark123jesper/bde952c2ee6d026689b587a56a2a0689 to your computer and use it in GitHub Desktop.
Different ways on how to use traditional Context and useContext Hook in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import ComponentB from './ComponentB' | |
const ComponentA = () => { | |
return ( | |
<div> | |
<div>ComponentA</div> | |
<ComponentB /> | |
</div> | |
) | |
} | |
export default ComponentA |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useContext } from 'react' | |
import ComponentC from './ComponentC' | |
import { NameContext, ColorContext } from '../Parent' | |
const ComponentB = () => { | |
const name = useContext(NameContext) | |
const color = useContext(ColorContext) | |
return ( | |
<div> | |
<div>ComponentB</div> | |
<div>name: {name} color: {color} </div> | |
<ComponentC /> | |
</div> | |
) | |
} | |
export default ComponentB |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { NameContext, ColorContext } from '../Parent' | |
const ComponentC = () => { | |
return ( | |
<div> | |
<div>ComponentC</div> | |
<NameContext.Consumer> | |
{name => { | |
return ( | |
<ColorContext.Consumer> | |
{color => ( | |
<div>name: {name}, color {color}</div> | |
)} | |
</ColorContext.Consumer> | |
) | |
}} | |
</NameContext.Consumer> | |
</div> | |
) | |
} | |
export default ComponentC; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ComponentA from './components/ComponentA' | |
export const NameContext = React.createContext() | |
export const ColorContext = React.createContext() | |
function Parent() { | |
return ( | |
<div> | |
<NameContext.Provider value={'Smith'}> | |
<ColorContext.Provider value={'red'}> | |
<ComponentA /> | |
</ColorContext.Provider> | |
</NameContext.Provider> | |
</div> | |
); | |
} | |
export default Parent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment