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>
);
}
Top comments (0)