I'm wondering if it's possible to create a context and consume it without passing the context down the whole section of the dom tree.
To that extent I've created the following example:
./components/count-context.js
import * as React from 'react'
const CountContext = React.createContext({count : 0} )
const CountContextProvider = (props) => {
const [count, setCount] = React.useState(0);
const incrementCount = () => {
console.log("increment count", count)
setCount(count + 1);
};
const decrementCount = () => {
setCount(count - 1);
}
return (
<CountContext.Provider value={{ count, setCount, incrementCount, decrementCount }}>
{props.children}
</CountContext.Provider>
);
}
const CountDisplayNoProvider = (props) => {
const { count } = React.useContext(CountContext)
return (
<p>{count}</p>
)
}
const CountDisplaySelfProvided = (props) => {
const { count } = React.useContext(CountContext)
return (
<CountContextProvider>
<p>{count}</p>
</CountContextProvider>
)
}
const IncrementCountButton = (props) => {
const { count, incrementCount, setCount } = React.useContext(CountContext)
console.log(`count is a `, typeof(count))
console.log(`incrementCount is a `, typeof(incrementCount))
console.log(`setCount is a `, typeof(setCount))
return (
<button onClick={incrementCount}>IncrementCountButton</button>
)
}
export {
CountContextProvider,
CountDisplayNoProvider,
CountDisplaySelfProvided,
IncrementCountButton
}
And: ./App.js
import './App.css';
import { CountContextProvider, CountDisplaySelfProvided, CountDisplayNoProvider, IncrementCountButton} from './components/count-context'
function App() {
return (
<div className="App">
<p>NO CONTEXT</p>
CountDisplayNoProvider: <CountDisplayNoProvider />
<IncrementCountButton />
<br />
CountDisplaySelfProvided: <CountDisplaySelfProvided />
<IncrementCountButton />
<CountContextProvider>
<p>CountDisplayNoProvider inside CountContextProvider</p>
<CountDisplayNoProvider />
<IncrementCountButton />
</CountContextProvider>
</div>
);
}
export default App;
The funny thing is that the CountDisplayNoProvider and CountDisplaySelfProvided both show a number: 0
but count-context.js:34 incrementCount is a undefined count-context.js:35 setCount is a undefined
--- so why is it that the count gets passed to NO CONTEXT, but not the functions?
And even stranger, why is it that I can't put the provider in the count's own component? (CountDisplaySelfProvided)
Thank you!!
Screenshot of the rendered output after rage clicking all the buttons
