Home > Mobile >  If I am unmounting a React component after some seconds, is the dependency array in Useeffect still
If I am unmounting a React component after some seconds, is the dependency array in Useeffect still

Time:03-26

I have a question concerning this particular example where I am using useEffect without dependency array. ESLint complains that it needs "navigate" inside the dependency array or else the dependency array can be removed.

Would this be a use case of useEffect without dependency array since I am unmounting the component after 3 seconds? Am I correct in thinking that we would not risk any re-render by not using a [] in this particular example?

//Home.js

export default function Home {
return <h1>Home</h1>
} 

//NotFound.js
import { useEffect} from 'react' 
import { useNavigate } from "react-router-dom";
export default function NotFound() {
  const navigate = useNavigate();

useEffect(() => {
setTimeout(() => navigate("/"), 3000)
})

return <h1>Not Found</h1>


//App.js

import "./styles.css";
import { Routes, Route } from "react-router-dom";

import NotFound from "./NotFound";
import Home from "./Home.js";
export default function App() {
  return (
    <div className="App">
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="*" element={<NotFound />} />
      </Routes>
    </div>
  );
}





It works with both the dependency array containing "navigate" and without the dependency array.

CodePudding user response:

You will risk re-render because, by default, the useEffect hook is triggered after each re-display. And with an array of dependencies, it runs once and then runs again with each change of the transmitted dependency. An empty array leaves no conditions for restarting the hook, ensuring that the message is received only when it is displayed for the first time. In this case use [].

CodePudding user response:

Why would we use useEffect without a dependency array? you might wanna check this one, so if you don't pass any dependency to useEffect it will rerun every time state or prop changes to avoid that you should use []. I understand that Eslint gives you warning about it for that you can check this question over here useEffect dependency array and ESLint exhaustive-deps rule. Hope you will find this answer helpful.

  • Related