React’s useEffect hook is a powerful tool for managing side effects in functional components. However, by default, the useEffect hook runs both on the initial render and whenever the component re-renders. In some cases, you may want to prevent the useEffect hook from running on the initial render. In this blog post, we will explore two solutions to achieve this.

Solution 1: Using a Ref

One way to make the useEffect hook not run on the initial render is by using a ref. By default, the value of a ref persists across re-renders, unlike regular variables. We can leverage this behavior to conditionally execute the effect only after the initial render.

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

function MyComponent() {
  const isInitialRender = useRef(true);

  useEffect(() => {
    if (isInitialRender.current) {
      isInitialRender.current = false;
    } else {
      // Your effect code here
    }
  }, []);

  return (
    // Your component JSX here
  );
}

Solution 2: Using a Dependency Array

Another approach is to use a dependency array in the useEffect hook. By providing an empty array as the dependency list, the effect will only run once, on the initial render. By adding dependencies to the array, the effect will re-run whenever any of the dependencies change.

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // Your effect code here
  }, []);

  return (
    // Your component JSX here
  );
}

Conclusion

By using either a ref or an empty dependency array, you can easily make the useEffect hook not run on the initial render. Choose the solution that best fits your specific use case.