To change a value in state we can do that directly (by pulling the atom with useRecoildState
), or we can write a custom hook that will change the value for us:
const useResetScore = () => {
const [score, setScore] = useRecoilState(gameScore)
return () => {
setScore(0)
}
}
That function returns a function that we can then call from a component like any other hook:
const resetScore = useResetScore()
and then we can use that new resetScore
function for the onClick
of a button:
<button onClick={resetScore}>Reset</button>
which will change the value in the Recoil state.
That's a simplistic example of a custom hook - but that hook could then be extended to do multiple state changes, and then could be imported into any component in the React tree and used.