|
| 1 | +# Side-Effect Cleanup |
| 2 | + |
| 3 | +In this extra credit we're going to use a completely different example. We're |
| 4 | +going to make a `<Tilt />` component that renders a div and uses the |
| 5 | +`vanilla-tilt` library to make it super fancy. |
| 6 | + |
| 7 | +The thing is, `vanilla-tilt` works directly with DOM nodes to setup event |
| 8 | +handlers and stuff, so we need access to the DOM node. But because we're not the |
| 9 | +one calling `document.createElement` (React does) we need React to give it to |
| 10 | +us. |
| 11 | + |
| 12 | +So in this exercise we're going to use a `ref` so React can give us the DOM node |
| 13 | +and then we can pass that on to `vanilla-tilt`. |
| 14 | + |
| 15 | +Additionally, we'll need to clean up after ourselves if this component is |
| 16 | +unmounted. Otherwise we'll have event handlers dangling around on DOM nodes that |
| 17 | +are no longer in the document which can cause a memory leak. |
| 18 | + |
| 19 | +To be clear about the memory leak, just imagine what would happen if we mount a |
| 20 | +tilt element, then unmount it (without cleaning up). Those DOM nodes hang around |
| 21 | +because the event listeners are still listening to events on them (even though |
| 22 | +they're no longer in the document). Then let's say we mount a new one and |
| 23 | +unmount that again. Now we have two sets of DOM nodes that are still in memory, |
| 24 | +but not being used. We keep doing this over and over again and eventually our |
| 25 | +computer is just keeping track of all these DOM nodes we don't need it to. |
| 26 | +That's what's called a memory leak. So it's really important we clean up after |
| 27 | +ourselves to avoid the performance problems associated with memory leaks. |
| 28 | + |
| 29 | +NOTE: Because this extra credit is a completely different example, you've got |
| 30 | +another starting point file in: `src/exercise/05.extra-1.tsx`. π¨ and π° will be |
| 31 | +there to help you get that working. |
| 32 | + |
0 commit comments