useEffect

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-23
Updated:
2019-08-15
Tags:
React libraries JavaScript

https://frontendmasters.com/courses/intermediate-react-v2/useeffect/

useEffect

  // ****Effect.js****


import React, { useState, useEffect } from "react";

const EffectComponent = () => {
  // setitng up the default `itme` value
  const [time, setTime] = useState(new Date());

  // this is delayed function
  // will not run on the first render but
  // after the rendering
  useEffect(() => {
    // notice that we are not using
    // setInterval 
    // because we are always rerendering
    // it could be done with setInterval as well though
    const timer = setTimeout(setTime(new Date()), 1000);
    return () => clearTimeout(timer);
    // it keeps running, because we didn't provide a
    // list of dependencies, as the second parameter
  });
    // if we would do
    // }, []);
    // then it would only run once
    // NOTE, according to the React team, 
    // you should do
    // }, [setTime]);
    // because it's a dependency, even though it's also a function
    // and so would never change
    // on the other hand, if you would do
    // }, [time]);
    // it would again run every 1000ms, because `time`
    // does change

  return <h1>useEffect Example: {time.toLocaleTimeString()}</h1>;
};

export default EffectComponent;

on clearing setTimeout

notice the code above

      return () => clearTimeout(timer);

it clears the Timeout, otherwise it can create some weird bugs. A the function that you return in useEffect is the cleanup function.

Great for integrating with other libraries.