Skip to content

Instantly share code, notes, and snippets.

@ynwd
Created January 21, 2022 10:03
Show Gist options
  • Save ynwd/218e4ba9b3837afba958dffc4bfa200c to your computer and use it in GitHub Desktop.
Save ynwd/218e4ba9b3837afba958dffc4bfa200c to your computer and use it in GitHub Desktop.
react createContext simple example
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