Created
January 22, 2022 01:47
-
-
Save ynwd/039a129a2f0eb29309fcbdad88cffee6 to your computer and use it in GitHub Desktop.
react useEffect & useContext 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, useEffect } from 'react' | |
function Counter() { | |
const { count, setCount } = useContext(CountContext) | |
useEffect(() => { | |
document.title = `You clicked ${count} times` | |
}, [count]) | |
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