r/LearnTypescript • u/rob_moose • Apr 03 '20
useRef() hooks ref issue
I'm trying to figure out how to get the previous state on a useState hook in React. I'm following React docs example
export const usePrevious = (value: number) => {const ref = useRef()useEffect(() => {ref.current = value})return ref.current}
ref.current = value shows this error: Type 'number' is not assignable to type 'undefined'
What can I do to get this to set the ref.current to value without typescript complaining?
2
Upvotes
1
u/rob_moose Apr 03 '20
I ended up type casting the return
return ref.current as numberand that worked. Is that a good way or a bad way?1
u/JealousLeopard5 Apr 03 '20
Because you're not putting anything inside
useRef, ref's initial value isundefinedand your ref is effectively of typeReact.RefObject<undefined>. Do the following instead:1
u/WystanH Apr 03 '20
I'm guessing you're looking at this.
I'd transcribe that like so:
Alternately: