Skip to content

Instantly share code, notes, and snippets.

@connorrose
Created November 9, 2020 02:33
Show Gist options
  • Save connorrose/c477efbe4307e01de75d317efcc6fada to your computer and use it in GitHub Desktop.
Save connorrose/c477efbe4307e01de75d317efcc6fada to your computer and use it in GitHub Desktop.
FEM btholt: useEffect hook example (Intermediate React v2)
import React, { useState, useEffect } from "react";
// Count useEffect calls (cumulative)
let ticks = 0;
const EffectComponent = () => {
const [time, setTime] = useState(new Date());
useEffect(() => {
console.log(++ticks); // Log count @ each call
// Move state update into anonymous function for setTimeout()
const timer = setTimeout(() => setTime(new Date()), 1000);
return () => clearTimeout(timer);
});
return <h1>useEffect Example: {time.toLocaleTimeString()}</h1>;
};
export default EffectComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment