Managing side effects such as data fetching, subscriptions, and manually changing the DOM can become challenging when building React applications. React's `useEffect` hook provides a powerful yet straightforward way to handle these side effects in function components. Let’s dive into the basics of `useEffect` to understand how it works and when to use it.
#### What is `useEffect`?
The `useEffect` hook is a function that allows you to perform side effects in function components. It runs after every render by default, making it ideal for operations that need to happen due to state or prop changes, such as fetching data from an API or updating the document title.
In this example, the document title updates every time the `count` state changes. The `useEffect` hook takes two arguments: a function and a dependency array. The function contains the side effect code, and the dependency array specifies when the effect should re-run. Here, `document.title` is updated whenever `count` changes.
When I first learn react, it was class components that I learnt. I was able to easily figure out the onmount having come from oop background. But getting to hooks, I got very confused and stuck with class components until much later. Now I will not even go near class components.