Skip to content

Instantly share code, notes, and snippets.

@RafaelFigueiredo
Created March 25, 2024 18:43
Show Gist options
  • Save RafaelFigueiredo/32ea6928bbd57da232c7746ef7243fe5 to your computer and use it in GitHub Desktop.
Save RafaelFigueiredo/32ea6928bbd57da232c7746ef7243fe5 to your computer and use it in GitHub Desktop.
Using context to update state in React
import { useState, createContext, useContext } from 'react'
import './App.css'
const StateContext = createContext<any>(null)
function Form() {
const { state, setState } = useContext(StateContext)
const handleClick = () => {
setState({
...state,
a: state.a +1,
b: state.b -1
})
}
return (
<div>
<h1>a: {state.a}</h1>
<h1>b: {state.b}</h1>
<button onClick={handleClick}>Add</button>
</div>
)
}
function App() {
const initial_state = {
a: 0,
b: 0,
}
const [state, setState] = useState(initial_state)
return (
<StateContext.Provider value={{ state, setState }}>
<Form />
</StateContext.Provider>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment