author avatar

sachin.kabadi

Tue Apr 16 2024

#nextJs #TypeScript
useEffect is a hook that allows you to perform side effects in function components.


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

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

  // This effect will run only when the count state changes
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]); // Only re-runs when count changes

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

export default MyComponent;


In the above example:
• We have a component MyComponent with a state variable count and a button to increment it.
• Inside the component, we use the useEffect hook to update the document title with the current count after each render.
• We pass [count] as the second argument to useEffect, which means the effect will only run when the count state changes. This is because we want to update the document title only when the count changes, not on every render.