Learn the basics of useEffect in just 60 seconds | React JS hooks #shorts

Posted by

Understanding useEffect in 60 seconds | React JS hooks

Understanding the basics of useEffect in 60 seconds | React JS hooks

If you’re new to React JS hooks, one of the most important ones to understand is useEffect. This hook allows you to perform side effects in your functional components. But what exactly does that mean?

When we talk about side effects in React, we’re referring to anything that affects something outside of the component. This could be fetching data from an API, subscribing to a WebSocket, updating the document title, and much more.

The useEffect hook takes two arguments: a function and an optional array of dependencies. The function is the side effect you want to perform, and the array of dependencies tells React when to re-run the effect. If the array is empty, the effect will only run once when the component mounts.

Here’s a quick example:

    
      import React, { useEffect, useState } from 'react';

      function App() {
        const [data, setData] = useState([]);

        useEffect(() => {
          fetch('https://api.example.com/data')
            .then(response => response.json())
            .then(data => setData(data));
        }, []);

        return (
          
{/* Render your component here */}
); } export default App;

In this example, the useEffect hook is used to fetch data from an API when the component mounts. The empty array of dependencies means that the effect will only run once.

That’s the basics of useEffect in React JS hooks in under 60 seconds. It’s a powerful tool for managing side effects in your functional components, and it’s essential for building modern, efficient React applications.