Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Created April 11, 2022 09:43
Show Gist options
  • Save lejonmanen/fed1d45194164ed29b735df55adca9f8 to your computer and use it in GitHub Desktop.
Save lejonmanen/fed1d45194164ed29b735df55adca9f8 to your computer and use it in GitHub Desktop.
React Context demo using hooks
import { createContext, useState, useContext } from 'react'
// Create the context in a separate file. Import it to every component that needs it.
const CounterContext = createContext(0)
const ContextDemo = () => {
const [count, setCount] = useState(2)
const contextValue = { count, setCount }
return (
<div>
<h3> Context demo </h3>
<CounterContext.Provider value={contextValue}>
<ViewChild />
<ViewChild />
<ViewChild />
<ViewChild />
<ViewChild />
<SetChild />
<SetChild />
</CounterContext.Provider>
</div>
)
}
// Doesn't matter how deep in the component hierarchy these components are.
const ViewChild = () => {
const { count } = useContext(CounterContext)
return (
<p> The count is {count}. </p>
)
}
const SetChild = () => {
const { setCount } = useContext(CounterContext)
return (
<p> <button onClick={() => setCount(c => c + 1)}> Increase count </button> </p>
)
}
export default ContextDemo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment