Last active
November 27, 2023 18:22
-
-
Save smitroshin/9315b6258ab90f5c7fe0644a9474a117 to your computer and use it in GitHub Desktop.
React hook - useStatefulRef
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 } 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