0
0
ReactHow-ToBeginner · 3 min read

How to Run Code on Mount in React Using useEffect Hook

In React, to run code only once when a component mounts, use the useEffect hook with an empty dependency array []. This tells React to run the effect only after the first render, similar to componentDidMount in class components.
📐

Syntax

The useEffect hook runs side effects in functional components. To run code on mount, pass a function as the first argument and an empty array [] as the second argument.

  • useEffect(() => { ... }, []): Runs the effect once after the component mounts.
  • The empty array means no dependencies, so the effect won't rerun on updates.
javascript
import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Code here runs once on mount
  }, []);

  return <div>Hello</div>;
}
💻

Example

This example shows a component that logs a message to the console only once when it mounts.

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

function Welcome() {
  useEffect(() => {
    console.log('Component mounted');
  }, []);

  return <h1>Welcome!</h1>;
}

export default Welcome;
Output
Welcome! (and console logs 'Component mounted' once)
⚠️

Common Pitfalls

Common mistakes include:

  • Omitting the dependency array, causing the effect to run after every render.
  • Adding dependencies unintentionally, which reruns the effect on updates.
  • Trying to run async code directly in useEffect without wrapping it in a function.
javascript
import React, { useEffect } from 'react';

// Wrong: runs on every render
function Wrong() {
  useEffect(() => {
    console.log('Runs every render');
  }); // no dependency array
  return <div>Wrong</div>;
}

// Right: runs only once on mount
function Right() {
  useEffect(() => {
    console.log('Runs once on mount');
  }, []);
  return <div>Right</div>;
}
📊

Quick Reference

Remember these points when running code on mount in React:

  • Use useEffect(() => { ... }, []) for code that runs once.
  • Empty dependency array means no reruns on updates.
  • Wrap async code inside the effect function.
  • Do not omit the dependency array unless you want the effect to run every render.

Key Takeaways

Use useEffect with an empty dependency array to run code once on mount.
Omitting the dependency array causes the effect to run after every render.
Wrap async code inside useEffect to avoid unexpected behavior.
The empty array signals React to skip rerunning the effect on updates.