ReactJS – useEffect hook

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see how to set up side-effects or HTTP requests in a functional component.

This hook is used to set up subscriptions, handle side-effects or to send analytics data to the server. It is the combination of componentDidMount, componentDidUpdate and componentWillUnmount methods of class-based components. The function passed to this hook will run only after the component is rendered.

Syntax

useEffect(()=>{},[]);
  • ()=>{} − Function passed to this hook

  • [ ] − It tells the hook when to re-render the component. For example −

    • [props] − If props values are changed then this hook is called again.

    • [ ] − This hook will be called once only when the component is rendered to the screen.

Example

In this example, we will build a React application that displays the message when the child component is mounted in the DOM.

App.jsx

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

function App() {
   return (
      <div className="App">
      <Comp1 />
      </div>
   );
}
function Comp1() {
   const [data, setData] = useState(null);
   useEffect(() => {
      setData('Component Mounted');
   }, []);

   return (
      <div>
         <h1>Tutorialspoint</h1>
         <h3>{data ? data : null}</h3>
      </div>
   );
}
export default App;

In the above example, useEffect hook is called only once when the Comp1 component is rendered on the screen.

Output

This will produce the following result.

raja
Published on 19-Mar-2021 10:47:33
Advertisements