Handle componentDidMount and componentWillUnmount in React Component Refactor to Hooks

Share this video with your friends

Send Tweet

Let's refactor our GitHubClientProvider class component to a function component that uses hooks. This one's pretty interesting because we can use useEffect to encapsulate everything we need for a single effect, truly separating that concern within our component.

Dean
Dean
~ 6 years ago

perhaps I am missing something, and I can't seem to locate it on your github. Your functions for logout / login are referecing setError and setClient, but how? Those state setters live in another function, so I am a little unsure how you are accessing them.

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

Hi Dean 👋 Give it a closer look. The state setters live within the closure of the GitHubClientProvider function and logout and login do as well, which is why they can access the state setters :)

Viktor Soroka
Viktor Soroka
~ 6 years ago

Hi Kent, I have a question about whether it is a good practice to place functions like logout and getClient within closure of the component. As I understand they are get's recreated on the every render. Thanks.

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

Hi Viktor, Two things about that:

  1. It wouldn't be possible because logout and getClient need access to variables that are defined within the closure of the function component.
  2. JavaScript is very fast and this will never be your app's performance bottleneck (unless you're creating thousands of these components in which case you should do a perf benchmark to determine if this is the problem and then you can do other optimizations).

I hope that helps.

Willis Plummer
Willis Plummer
~ 6 years ago

Hey Kent, in these videos you convert arrow functions to function() syntax from time to time but it's unclear to me what the reasoning is behind when you do this. e.g. in this video at 05:34. Could you explain what the distinction you're making is?

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

It really doesn't matter all that much which is why I don't really make much of a mention of it. For me it's mostly a preference. Maybe this will provide additional insight: https://www.briefs.fm/3-minutes-with-kent/64

Willis Plummer
Willis Plummer
~ 6 years ago

Gottcha - I was just thrown because you were alternating between the two syntaxes. Was wondering if I was missing something important. Thanks for the quick reply!

Hallya
Hallya
~ 5 years ago

7:10 -> Not sure about having 2 behavior in one function is more simple to understand but sure it is shorter