useEffect() Hook in React JS

  • The useEffect() hook is a built-in hook in React that allows functional components to perform side effects. Side effects are operations that affect something outside the component, such as fetching data from an API, updating the document title, or setting a timer.
  • The useEffect() hook takes two arguments: a function that performs the side effect, and an optional array of dependencies that tells React when to run the effect.
Here is an example of how to use useEffect():

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

function Example() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        document.title = `You clicked ${count} times`;
    }, [count]);

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
    );
}
  • In this example, we start by importing the useEffect hook from React. We then define a functional component called Example and use the useState hook to define a state variable called count with an initial value of 0.
  • We then use the useEffect hook to set the document title to display the current count. We pass a function as the first argument to useEffect that updates the document title with the current count. We also pass an array containing the count state as the second argument to useEffect. This tells React to only run the effect when the count state changes.
  • In the return statement, we use the count state to display the number of times the button has been clicked. We also attach an onClick event to the button that calls the setCount function with a new value that increments the current count.
  • By using the useEffect hook, we can perform side effects in a functional component, which allows us to separate the concerns of our application and make it easier to manage complex logic in our React applications.

No comments:

Post a Comment

Mathematical Aggregation Functions ($mod, $abs, $round, $exp, $log, $log10, $pow, $sqrt, $trunc, $sin, $cos, $tan, $degreesToRadians, $radiansToDegrees, $round, $ceil, $floor)

MongoDB  Mathematical  Aggregation Functions with Examples Step 1:  Insert a Dataset into MongoDB Collection First, we'll insert a sampl...