Created
March 25, 2024 18:43
-
-
Save RafaelFigueiredo/32ea6928bbd57da232c7746ef7243fe5 to your computer and use it in GitHub Desktop.
Using context to update state in React
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 { 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