Hooks 2: useEffect useLayoutEffect


useEffect

Render once after ui is rendered.

useEffect(() => {
    // do this once.
},[])
useEffect(() => {
    const waterMarks = document.getElementsByClassName('leaflet-control-attribution')
    for (let i =0; i < waterMarks.length; i++) {
        document.getElementsByClassName('leaflet-control-attribution')[i].style.display = 'none';
    }
},[])
    
Respond to changes.

useEffect(() => {
    // do this when the param is changed
},[param])
useEffect(() => {
    const getVisitorInfo = async () => {    
        let currentTimestamp = Date.now()
        let date = new Intl.DateTimeFormat('en-US',
            {year:'numeric',month:'2-digit',day:'2-digit',
            hour:'2-digit',minute:'2-digit',second:'2-digit'})
            .format(currentTimestamp)
        const ip = await publicIp.v4({fallbackUrls:["https://ifconfig.co/ip"]});
          console.log(ip,date)
        fetch("https://ipapi.co/"+ip+"/json/")
          .then((response) => response.json())
          .then((data) => {
              const {ip,country_name,latitude,longitude} = data;
              const ignoreIP = process.env.REACT_APP_IGNORE_IP.split(",")
              if (selected!=="" && ip && ignoreIP.indexOf(ip)<0 ){
                  const objt = {IP:ip,Topic:selected,
                      Timestamp:date,Country:country_name,
                      Lat:latitude,Lng:longitude};
                  axios.post(sheeturi,objt)
                      .then((response) => {
                          console.log(response);
                      });
              }
          })
          .catch(e=>{})

      }
    getVisitorInfo();
    }, [selected]);
    
Loop

useEffect(()=>{
}) # no dependency list
    

useLayoutEffect

References