Dev.to AI 🤖 Ai 👁 0

ReactJS useEffect Hook

The *useEffect * hook is one of the most commonly used hooks in ReactJS, used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle m

ReactJS useEffect Hook

The *useEffect * hook is one of the most commonly used hooks in ReactJS, used to handle side effects in functional components. Before hooks, these kinds of tasks were only possible in class components through lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

Fetching data from an API.
Setting up event listeners or subscriptions.
Manipulating the DOM directly (although React generally handles DOM manipulation for you).
Cleaning up resources when a component unmounts.

Syntax

useEffect(() => {
// Code to run on each render
return () => {
// Cleanup function (optional)
};
}, [dependencies]);

Working of useEffect

//HookCounterOne.js

// useEffect is defined here

import { useState, useEffect } from "react";

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

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

    return (
        <div>
            <button onClick={() => setCount((prevCount) => prevCount + 1)}>
                Click {count} times
            </button>
        </div>
    );
}
export default HookCounterOne;

//App.js

//App.js 

// Importing and using HookCounterOne

import React from "react";
import "./App.css";
import HookCounterOne from "./components/HookCounterOne";

function App() {
    return (
        <div className="App">
            <HookCounterOne />
        </div>
    );
}
export default App;

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.