Skip to content

Instantly share code, notes, and snippets.

@ynwd
Created January 22, 2022 01:47
Show Gist options
  • Save ynwd/039a129a2f0eb29309fcbdad88cffee6 to your computer and use it in GitHub Desktop.
Save ynwd/039a129a2f0eb29309fcbdad88cffee6 to your computer and use it in GitHub Desktop.
react useEffect & useContext example
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