Last active
May 17, 2023 07:10
-
-
Save Arkellys/8a4e5e145f7cf13ef833465614986f3a to your computer and use it in GitHub Desktop.
Custom hook like `useState()` but updates the state when the initial value changes.
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 { useEffect, useState } from "react"; | |
/** | |
* Returns like `useState()` but updates the state when the initial value changes. | |
* @param {any} initialValue - Initial value of the state | |
* @returns {Array.<any,Function>} State value and setter | |
*/ | |
export function useStateWithEffect(initialValue) { | |
const [value, setValue] = useState(initialValue); | |
useEffect(() => { | |
setValue(initialValue); | |
}, [initialValue]); | |
return [value, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment