Last active
November 24, 2021 16:32
-
-
Save ItsJonQ/4598a0d203049b329965484676ca11d4 to your computer and use it in GitHub Desktop.
react-use-controlled-state.js
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, useEffect, useRef } from "react"; | |
export function useControlledState(initialState) { | |
const [state, setState] = useState(initialState); | |
const stateRef = useRef(initialState); | |
useEffect(() => { | |
if (initialState !== stateRef.current) { | |
setState(initialState); | |
stateRef.current = initialState; | |
} | |
}, [initialState]); | |
return [state, setState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment