Evan Cordulack

Refactoring Using React Hooks: useEffect and Input Fields

January 25, 2020

While refactoring the app I use for creating example text 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.

Source: https://reactjs.org/docs/hooks-effect.html

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 e.target as you normally would with vanilla JS.