Im not as versed in React but doesn’t componentWillUnmount happen once you leave the page. So it would still set the message in the state until you leave the page.
Hopefully someone with more React experience can help out.
Nothing runs when you leave the page; the entire app is destroyed when that happens. componentWillUnmount runs when the component is about to be removed from the virtual DOM in a still-running app. It’s usually used to stop timers and other outside resources – basically it’s a destructor/finalizer.
It’s also not something you need for normal components… which leads me to a mini-rant: This particular challenge is absolutely ridiculous and wrong. React was created, in part, in order to get away from manually hooking up and destroying event listeners like this. The lesson is very much teaching the wrong way to use React, and should be removed from the curriculum.
Well I definitely need to get back into React, I’ve worked in Vue mostly and haven’t really used anything like componentWillUnmount before. I was referencing more of leaving that component and rendering a new component not leaving the app, I did poorly write that.
I’ve been using Vue.js in a serious project for a few months now, and while it feels a little “dirtier” than React+JSX to write things with, I’m blown away by how powerful it is.
Anyhoo, the Vue equivalent to componentWillUnmount is beforeDestroy(). The diagram in this post is super useful, along with everything else on alligator.io:
Sorry, I don’t mean to hijack this into a Vue thread. Let’s tackle the problem, shall we?
@OJL Could you describe what you mean when you say removing the event listeners didn’t work? Your code looks all right to me at first glance. Are any of the tests failing?
You’re seeing the desired effect: the component on the page is still there when you hit enter, so it’s still listening. The listener gets removed in the componentWillUnmount method, which only gets called once the component gets removed. In this case, since there’s nothing on the page that will remove that component until you leave the page, it’ll never actually get run.
Thank you.
That’s correct,
react docs say same thing.
“We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.”
“If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle method so the timer is stopped.”