Skip to content

Instantly share code, notes, and snippets.

@raffleberry
Last active April 26, 2021 19:45
Show Gist options
  • Save raffleberry/daebbd4b596934b7389e42ed2ebbaf5e to your computer and use it in GitHub Desktop.
Save raffleberry/daebbd4b596934b7389e42ed2ebbaf5e to your computer and use it in GitHub Desktop.
React Context Template
// source: https://medium.com/swlh/this-is-how-to-use-the-react-context-api-with-hooks-for-a-clean-code-architecture-2019-e66662ec7ab8
const AppContext = createContext();
function AppContextProvider({ children }) {
const [amount, setAmount] = useState(0);
function deposit(value) {
setAmount(amount + value);
}
function withdraw(value) {
const newAmount = amount - value;
setAmount(newAmount < 0 ? 0 : newAmount);
}
const defaultContext = {
amount,
deposit,
withdraw
};
return (
<AppContext.Provider value={defaultContext}> // Look here!
{children}
</AppContext.Provider>
);
}
// Wrap the AppContext Provider
render(
<AppContextProvider>
<App />
</AppContextProvider>,
document.getElementById('root')
);
// useContext() example
function App() {
const { amount, deposit, withdraw } = useContext(AppContext);
return (
<div className="app-container">
<Amount value={amount} />
<div className="separator" />
<Controls onDeposit={deposit} onWithdraw={withdraw} />
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment