Skip to content

Instantly share code, notes, and snippets.

@ItsJonQ
Last active November 24, 2021 16:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ItsJonQ/4598a0d203049b329965484676ca11d4 to your computer and use it in GitHub Desktop.
Save ItsJonQ/4598a0d203049b329965484676ca11d4 to your computer and use it in GitHub Desktop.
react-use-controlled-state.js
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