Created
January 21, 2022 10:03
-
-
Save ynwd/218e4ba9b3837afba958dffc4bfa200c to your computer and use it in GitHub Desktop.
react createContext simple example
This file contains 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 React, { useContext, useReducer, createContext } from 'react' | |
function Counter() { | |
const { count, setCount } = useContext(CountContext) | |
return ( | |
<div> | |
<p>You clicked {count} times</p> | |
<button onClick={() => setCount(count + 1)}> | |
Click me | |
</button> | |
</div> | |
) | |
} | |
const CountContext = createContext() | |
function countReducer(state, count) { | |
console.log("count=", count) | |
console.log("state=", state) | |
return count | |
} | |
function App() { | |
const initialvalue = 1 | |
const [count, setCount] = useReducer(countReducer, initialvalue) | |
return ( | |
<CountContext.Provider value={{ count, setCount }}> | |
<Counter></Counter> | |
</CountContext.Provider> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment