1

I am coming over from class styled React components and learning hooks. Can I just use useEffect how I would would use componentDidMount lifecycle method? For example, can I import a function and just call it within useEffect() to mimic how componentDidMount would work?

import { myFunc } from './importedFuncs';

export default function User() {
    useEffect(() => {
        myFunc();
    });
megank3
  • 65
  • 3
  • `useEffect` without a dependency array, as in your example, is an equivalent of `componentDidMount` AND `componentDidUpdate`. https://reactjs.org/docs/hooks-effect.html If you want to use it as just `componentDidMount`, add an empty array `...}, []);` – codemonkey Feb 09 '21 at 20:59
  • Does this answer your question? [React - useEffect hook - componentDidMount to useEffect](https://stackoverflow.com/questions/56249151/react-useeffect-hook-componentdidmount-to-useeffect) – codemonkey Feb 09 '21 at 21:05

2 Answers2

1

To have an useEffect equivalent to componentDidMount, use the empty array [] as the second argument. An empty dependency list ensures the function is executed just once, on the first render.

Dan
  • 9,912
  • 18
  • 49
  • 70
0

You can use useEffect(() => {//some code}, []) to mimic the old componentDidMount function. some code will only run once on the first render. You can read this article to better understand the useEffect hook.

Silidrone
  • 1,471
  • 4
  • 20
  • 35