Skip to content

Instantly share code, notes, and snippets.

@Arkellys
Last active May 17, 2023 07:10
Show Gist options
  • Save Arkellys/8a4e5e145f7cf13ef833465614986f3a to your computer and use it in GitHub Desktop.
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.
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