DEV Community

Pasindu Laksara
Pasindu Laksara

Posted on

useEffect Hook with simple example

In this example, we define a component called Example that uses the useEffect hook.

First, we define a state variable count using the useState hook.

Inside the useEffect hook, we update the title of the document using the document.title property. The useEffect hook takes a function as its first argument that will be called after the component has been rendered. In this case, we're updating the document title to reflect the current value of count. We also pass an array [count] as the second argument to useEffect, which tells React to only re-run the effect when the count state variable has changed.

Finally, we render the current value of count using an HTML paragraph element and a button that updates the count state variable when clicked.

This simple example demonstrates how we can use the useEffect hook in a React component to perform side effects, such as updating the title of the document based on the current state of the component.

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

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

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

  const handleButtonClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={handleButtonClick}>Click me</button>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️