useEffect

useEffect lets you perform side effects in function components.

Sometimes, we want to run some additional code after React has updated the DOM.

This hook tells React that your component needs to do something after render.

This runs asyncronously, so it won't block the DOM loading, but it can cause some errors as a result.

Network requests, manual DOM mutations, and logging are common examples of effects that don't require a cleanup.

Previously, this is what componentDidMount, componentDidUpdate and the like were used for.

React will remember the function you passed, and call it later after performing the DOM updates.

It runs both after the first render and after every update, making it good for API calls.

This example follows on from the useState example.

In addition to the count that useState gave us, we're now also updating the DOM.

useEffect(() => {document.title = `${count} clicks`;});

Worth bearing in mind that while the examples from above don't require cleanup, some examples do, in order to avoid security issues.

An example that would require cleanup is a subscription to an external API.

I need to look into this 'cleanup' more to understand it fully.

Example

You clicked 0 times! Look at the title in your tab bar, too.