Control component side effects with React useEffect

Share this video with your friends

Send Tweet

The useEffect hook is used to handle side-effects caused by a component's actions such as fetching data from an API, attaching event listeners to the document or manipulating the DOM itself.

useEffect takes two values: a function defining the logic to be executed and an optional array called the "dependency array". By default, effect hooks will run every time the component re-renders, however, you can control its execution by defining and changing the values within your dependency array.

useEffect(() => {
	// Runs every time the component renders
})

useEffect(() => {
	// Runs only on initial render
}, []) // Optional second argument: dependency array

useEffect(() => {
	// Runs only when 'apiData' changes
}, [apiData])
Maven
Maven
~ 3 years ago

The NASA API returns a 200 but the incorrect data. It returns empty dayData. On app, I see this error:

TypeError: Cannot read properties of undefined (reading 'mn')