Skip to content

Instantly share code, notes, and snippets.

@smitroshin
Last active November 27, 2023 18:22
Show Gist options
  • Save smitroshin/9315b6258ab90f5c7fe0644a9474a117 to your computer and use it in GitHub Desktop.
Save smitroshin/9315b6258ab90f5c7fe0644a9474a117 to your computer and use it in GitHub Desktop.
React hook - useStatefulRef
import { useState } from "react";
/**
* As an API it's the same useRef,
* but it uses useState under the hood.
*
* Used to watch the ref changing between re-renders.
*
* Source: https://non-traditional.dev/creating-a-stateful-ref-object-in-react-fcd56d9dea58
*/
export function useStatefulRef<T extends unknown>(initialVal: T | undefined = undefined) {
let [currentVal, setCurrentVal] = useState<T | undefined>(initialVal);
const [statefulRef] = useState({
get current() {
return initialVal;
},
set current(value) {},
});
Object.defineProperty(statefulRef, "current", {
get: () => currentVal,
set: (newValue) => {
if (!Object.is(currentVal, newValue)) {
currentVal = newValue;
setCurrentVal(newValue);
}
},
});
return statefulRef;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment