Issue
I have the following code in my react component:
const [counter, setCounter] = useState(5);
const unMount = useRef();
unMount.current = () => { // <- gives error "Type '() => void' is not assignable to type 'undefined'"
console.log(`The counter is: ${counter}`);
};
useEffect(() => {
return () => {
if (unMount.current)
unMount.current();
};
}, [])
I need to access the counter variable in the cleanup function of my useEffect hook. And the cleanup needs to run on component unmount only. Also, the counter may change between the first and last render of the component. I have found the following guide for achieving my goals, but when I try to assign a function to the useRef's current object, I get the error Type '() => void' is not assignable to type 'undefined'
.
I'm new to React and think I'm missing something with my hook declaration, but I'm not sure what. There are some similar cases on SO, but they don't have the same error message and they don't deal with hooks. Why am I getting the Type '() => void' is not assignable to type 'undefined'
error?
Solution
If you are using typescript declare a type along with the useRef hook
const unMount = useRef<()=>void>();
Answered By - Halogen09
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.