OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

React Router useNavigate with a useEffect hook - proper way to use?

  • Thread starter Thread starter user15041164
  • Start date Start date
U

user15041164

Guest
I'm new to React and trying to make a loading/greeting page that navigates on to the next after a few seconds of being shown. In React Router v6, we have the useNavigate() hook to allow you to control the navigation, and I am using this to successfully call the navigate function by setting a timeout in a useEffect() hook. However, the compiler is complaining that I have a missing dependency. I only want it to run once though, not whenever the navigate changes. What is the best way to do this?

Thanks!

Code:
import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

function Greeting(props) {
  const navigate = useNavigate();
  useEffect(() => {
    setTimeout(() => navigate(props.nextPage), 3000);
  }, []);

  return (
    <div className="Greeting">
      <div>Hello World!</div>
    </div>
  );
}

export default Greeting;
Line 9:6: React Hook useEffect has a missing dependency: 'navigate'. Either include it or remove the dependency array react-hooks/exhaustive-deps

<p>I'm new to React and trying to make a loading/greeting page that navigates on to the next after a few seconds of being shown. In React Router v6, we have the <code>useNavigate()</code> hook to allow you to control the navigation, and I am using this to successfully call the navigate function by setting a timeout in a <code>useEffect()</code> hook. However, the compiler is complaining that I have a missing dependency. I only want it to run once though, not whenever the <code>navigate</code> changes. What is the best way to do this?</p>
<p>Thanks!</p>
<pre class="lang-js prettyprint-override"><code>import { useEffect } from "react";
import { useNavigate } from "react-router-dom";

function Greeting(props) {
const navigate = useNavigate();
useEffect(() => {
setTimeout(() => navigate(props.nextPage), 3000);
}, []);

return (
<div className="Greeting">
<div>Hello World!</div>
</div>
);
}

export default Greeting;

</code></pre>
<blockquote>
<p>Line 9:6: React Hook useEffect has a missing dependency: 'navigate'. Either include it or remove the dependency array react-hooks/exhaustive-deps</p>
</blockquote>
 

Latest posts

Top