Reputation: 312
I have been working on a project, and I want a div ID before unmounting it.
I tried using the below code:
useEffect(()=>
return()=>getId
),[state])
but the div was set to null before it came to useEffect.
To figure it out, I wrote an example code, and from that, I observed something really odd React is rendering component before it unmounts.
you can see similar behavior on clicking test button in above mention code.
If someone has any idea how it works, Please explain or suggest any alternate method.
Upvotes: 0
Views: 353
Reputation: 1011
Returning a function from a useEffect allows you to clean up after yourself, like removing event listeners and unsubscribing from something. It shouldn't really be thought of as an "unmount" callback.
If you want to know what element you're going to be removing with a button click, you could partially apply a function when you give the click handler to the button. This allows you to have a single click handler for all your buttons, where you give it a bit of extra context depending on where you implement it.
const handleClick = (id: string) => (event: ChangeEvent<HTMLButtonElement>) => {
// ...handle the click
}
// ...in your render fn
<button onClick={handleClick("div-id-1")}>Remove Div 1</button>
Upvotes: 0