Skip to content

Instantly share code, notes, and snippets.

@kcoyner
Created January 19, 2021 12:11
Show Gist options
  • Save kcoyner/f7303c0a56b7fc2e9b32d76ea7d97035 to your computer and use it in GitHub Desktop.
Save kcoyner/f7303c0a56b7fc2e9b32d76ea7d97035 to your computer and use it in GitHub Desktop.
example of useContext
import React, { useState } from 'react';
// Create a Context
const MyContext = React.createContext();
// It returns an object with 2 values: { Provider, Consumer }
function ParentComponent() {
const [counter, setCounter] = useState(0);
// Create an object containing both the value and the setter
const contextValue = {counter, setCounter};
return (
<MyContext.Provider value={contextValue}>
<SomeChildComponent />
</MyContext.Provider>
)
}
// ---------- some other page --------- //
import React, { useContext } from 'react';
function NestedChildComponent() {
const { counter, setCounter } = useContext(MyContext);
// do something with the counter value and setter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment