Use React Hooks to Convert a Class Component to a Function Component

Elijah Manor
InstructorElijah Manor
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 5 years ago

React just announced a new [Hooks](Introducing Hooks – React) proposal enabling React Function Components to handle state and side-effects, which was previously only possible with React Class Components. In this lesson, we will be using a prerelease of React to convert a React Class Component to a Function Component using hooks, and then at the very end we'll introduce a custom hook to simplify the component even further.

Prodigious
Prodigious
~ 5 years ago

Since this is adding and removing an event listener after each render, a little optimization can be applied here, using [] as second argument to useEffect, this means that this effect doesn't have dependencies on it and it doesn't need to be reapplied every render, so react only applies it once and clean it once, sort of a componentDidMount and componentWillUnmount combined into one effect.

Tony Brown
Tony Brown
~ 5 years ago

the app starts then errors out?

Elijah Manor
Elijah Manorinstructor
~ 5 years ago

Tony, doh! My package.json didn't reflect what I was running. I updated the package.json/lock and pushed it back up. Please try again. Thanks for pointing that out

Elijah Manor
Elijah Manorinstructor
~ 5 years ago

Prodigious, nice eye and it sure does look like there would be multiple listeners after using the app for a while.

Here is a snippet from the docs about useEffect https://reactjs.org/docs/hooks-effect.html

"React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time."

It would have been better for me to use the 2nd argument, but there is actually quite a bit to that little piece of code to cover (what it does with nothing, what it does with an empty array, what it does with a non-empty array).

What I'd probably do in this case is provide an empty array which would only wire things up once and clean-up only once. See following from docs...

"If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument."

AdFire
AdFire
~ 5 years ago

Can I like this twice?? Great explanation. Thanks!

Markdown supported.
Become a member to join the discussionEnroll Today