Created
December 14, 2022 13:55
-
-
Save nexpr/79192a32765ebf7248460cd25c43e1bd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useContext, createContext } from "react" | |
const CounterContext = createContext() | |
const CounterProvider = CounterContext.Provider | |
const useCounter = () => useContext(CounterContext) | |
const useNewCounter = () => { | |
const [count, setCount] = useState(0) | |
return { | |
count, | |
up: () => setCount(x => x + 1) | |
} | |
} | |
const useChainCounter = () => { | |
const parent_counter = useCounter() | |
const counter = useNewCounter() | |
return { | |
...counter, | |
up: () => { | |
counter.up() | |
parent_counter?.up() | |
} | |
} | |
} | |
const Parent = () => { | |
const counter = useNewCounter() | |
return ( | |
<CounterProvider value={counter}> | |
<Button /> | |
<hr /> | |
<Child /> | |
<hr /> | |
<Button /> | |
</CounterProvider> | |
) | |
} | |
const Child = () => { | |
const chain_counter = useChainCounter() | |
return ( | |
<CounterProvider value={chain_counter}> | |
<Button /> | |
<Button /> | |
</CounterProvider> | |
) | |
} | |
const Button = () => { | |
const counter = useCounter() | |
return ( | |
<button onClick={counter.up}>{counter.count}</button> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment