DEV Community

Pranav Bakare
Pranav Bakare

Posted on

UseEffect in React

Welcome to the world of React Hooks! Today, we'll dive into one of the most popular hooks: useEffect. Don't worry, we'll make it fun and easy to understand. So, let's get started! πŸš€

πŸ“š What is useEffect

useEffect is a React Hook that allows you to perform side effects in your functional components. Side effects are actions that happen outside of your component, like fetching data, updating the DOM, or subscribing to events. With useEffect, you can manage these side effects without writing a class or function. πŸŽ‰

πŸ§ͺ How useEffect works

useEffect is like a Swiss Army knife πŸ‡¨πŸ‡­πŸ”ͺ for side effects in your functional components. It combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount from class components into one simple hook.

Here's how it works:

  1. You call useEffect with a function that contains your side effect.
  2. React runs your side effect function after rendering the component.
  3. If you provide a cleanup function, React will call it when the component is unmounted or when the dependencies change.

No need to write a class or function! 🀯

⚑ Different use cases

Let's explore some common use cases for useEffect:

Fetching data: You can use useEffect to fetch data from an API and update your component's state when the data is received. πŸ“¦
Updating the document title: Want to change the title of your webpage based on the component's state? useEffect to the rescue! πŸ¦Έβ€β™‚οΈ
Setting up event listeners: Need to listen for events like window resizing or keyboard input? useEffect can help you set up and clean up event listeners. 🎧
Persisting state: Want to save your component's state to local storage or a database? useEffect can handle that too! πŸ’Ύ
Timers and intervals: If you need to set up a timer or interval in your component, useEffect is the perfect tool for the job. You can start the timer when the component mounts and clear it when the component unmounts. ⏳

Top comments (0)