replacing componentDidMount with useEffect

Viewed 6230

I was going through React Hooks docs and it mentioned

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Suppose I have a class component right now where in componentDidMount I am doing something like this

  componentDidMount() {
    MapboxGL.setTelemetryEnabled(false);
  }

As far as I can recall, Component did mount is only called once in lifecycle?

If I were to use react hooks then it would be something like this

  useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
  });

This would call my function everytime state changes in react functional hooks component? Wouldn't it be redundant to call MapboxGL.setTelemetryEnabled(false); to call this everytime? when you only want to do it once component have mounted?

React docs have showed how useEffect can replace multiple lifecycle methods but I am still unable to comprehend how react hooks can replace componentDidMount?

Also, Just a side note question, Can you make a full fledge app using hooks (something like foursquare or instagram?)

2 Answers

You need to add a dependency array for it to know when to recall this hook. An empty dep array will only call it once aka "on mount". And if you don't provide a dep array then it will just be called on every re-render.

useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
}, []);

You can create a flag and if the flag is false/true then only perform that action. something as simple as this

 useEffect(() => {
   if (something) {
    MapboxGL.setTelemetryEnabled(false);
    setSomething(false) 
    }
  });

or if you only need hook once, you can do what Matt have suggested

useEffect(() => {
   MapboxGL.setTelemetryEnabled(false);
}, []);
Related