Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React hooks refactor #1

merged 2 commits into from Jan 3, 2020

React hooks refactor #1

merged 2 commits into from Jan 3, 2020


Copy link

@cordulack cordulack commented Jan 3, 2020

While refactoring this small app to use React Hooks, I found I needed to look up a few things in order to get things working:

When swapping over to useEffect() from a componentDidMount(), the text kept refreshing and wouldn't stop.

What ended up happening was that the app generated some paragraphs when the component mounted and updated the state when it did that. This update triggered another call to useEffect() which started us into an infinite loop. The useEffect() hook allows you to only run your code one time.

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. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.


To fix this, it was a matter of passing in an empty array as the second argument to useEffect()

How do I update state using the value in an input field?

You have access to the event object in the onChange prop, so you can use as you normally would with vanilla JS.

@cordulack cordulack merged commit f76f8ab into master Jan 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
None yet
1 participant