Using the useContext
hook with React 16.8+ works well. You can create a component, use the hook, and utilize the context values without any issues.
What I'm not certain about is how to apply changes to the Context Provider values.
1) Is the useContext hook strictly a means of consuming the context values?
2) Is there a recommended way, using React hooks, to update values from the child component, which will then trigger component re-rendering for any components using the useContext
hook with this context?
const ThemeContext = React.createContext({
style: 'light',
visible: true
});
function Content() {
const { style, visible } = React.useContext(ThemeContext);
const handleClick = () => {
// change the context values to
// style: 'dark'
// visible: false
}
return (
<div>
<p>
The theme is <em>{style}</em> and state of visibility is
<em> {visible.toString()}</em>
</p>
<button onClick={handleClick}>Change Theme</button>
</div>
)
};
function App() {
return <Content />
};
const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.2/umd/react-dom.production.min.js"></script>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…