The useEffect
hook in React is used to manage side effects in functional components. It's a powerful and versatile tool that can be used to handle a variety of scenarios. Here are some better use cases of useEffect
hook with examples:
- Fetching Data
One of the most common use cases of useEffect
is fetching data from an API. For example, let's say you want to fetch a list of todos from an API when a component mounts:
In this example, the useEffect
hook is used to fetch data from the API when the component mounts. The empty array []
as a second argument tells React that the effect should only run once, when the component mounts.
2. Updating the DOM
Another use case of useEffect
is updating the DOM in response to state changes. For example, let's say you want to update the document title to reflect the current page tittle.
In this example, the useEffect
hook is used to update the document title when the pageTitle
state changes. The pageTitle
state is updated when the user types in the input field.
3. Subscribing to Events
useEffect
can also be used to subscribe to events like window
resize events or key press events. For example, let's say you want to log the window dimensions when the user resizes the window
In this example, the useEffect
hook is used to subscribe to the window
resize event and update the windowDimensions
state accordingly. The empty array []
as a second argument tells React that the effect should only run once, when the component mounts. The return function inside useEffect
is used to remove the event listener when the component unmounts.
These are just a few examples of how useEffect
can be used in React. There are many more use cases depending on your application requirements.