DEV Community

Discussion on: React Hooks Explained: useImperativeHandle

Collapse
 
prancer profile image
Jason Gretz

What you have setup with the useEffect works because it's nearly identical to useImperativeHandle. The difference, and the reason you want to use useImperativeHandle, is because in addition to the side effect, useImperativeHandle will automatically cleans up the reference when the child component unmounts.
Of course, you can add that logic yourself in the useEffect hook, but you'd have to remember to add that logic every time you have this situation. React has the information it needs to perform that logic for you automatically. This helps to prevent memory leaks and unreachable code.