Reference

https://react.dev/reference/react/useEffect

 

1. Used to connect to external systems such as the browser API  or a server.

 Keep code in here that needs to step outside of React app.

Note: One could use similar code inside of an event handler.

 

Introduction to useEffect

  • useEffect(effectFn, deps?)

 

  • use for side-effects

 

  • effectFn: function that can have side-effects; optionally return cleanup function

 

  • deps: a list of values that the side-effect depends on (optional)

 

  • when dependencies change, the effect is cleaned up and ran again

 

  • if no dependencies are given, then the effect runs on every render

 

 

 This is a listener for changes on the dependencies.

If one of the dependencies changes then run a function.

 

If there are no dependencies then the function runs every render.

 

import React, { FC, useEffect, useState } from 'react'
export const LocaleClock: FC<{ locale?: string }> = ({ locale = 'en-US' }) => {
  const [timeString, setTimeString] = useState<string>()
  useEffect(() => {
    const update = () => {
      setTimeString(new Date().toLocaleTimeString(locale))
    }
    update()
    const interval = window.setInterval(update, 500)
    return () => {
      window.clearInterval(interval)
    }
  }, [locale])
  return <p>{timeString}</p>
}
export const ToggleLocale: FC = () => {
  const [locale, setLocale] = useState('en-GB')
  const toggleLocale = () => {
    setLocale(locale === 'en-GB' ? 'th-TH-u-nu-thai' : 'en-GB')
  }
  return (
    <>
      <button type="button" onClick={toggleLocale}>
        toggle locale
      </button>
      <LocaleClock locale={locale} />
    </>
  )
}
export default <ToggleLocale />