DEV Community

Harry J Beckwith
Harry J Beckwith

Posted on

React Hooks useEffect()

Using hooks in javascript is a way to tuck into pre built methods that come with React 16.8 up.

What is it?

The Effect hook is used to prevent infinite loops occurring within you applications. It allows you to perform side effects in function components.

For example on landing on the page, the logic inside the component, triggers a state change on page load. The component now re renders (due to the state change), which then calls the logic again, this creates an infinite loop.

Using Effect allows to control when the logic can be called. Avoiding the infinite loop.

How to use it?

import React, { useEffect } from 'react';
Enter fullscreen mode Exit fullscreen mode
useEffect(()=>{},[])
Enter fullscreen mode Exit fullscreen mode

The Effect hook, takes a function and an array of dependencies.

When to use it?

Used when the page is reloaded to check logic and update state. Or when returning to a page.

Also to re run logic when state has been changed.

Code example

  const [enteredEmail, setEnteredEmail] = useState('');
  const [formIsValid, setFormIsValid] = useState(false);

 useEffect(() => {
    setFormIsValid(
      enteredEmail.includes('@')
    );
  },[enteredEmail])

  const emailChangeHandler = (event) => {
    setEnteredEmail(event.target.value);
  };
Enter fullscreen mode Exit fullscreen mode

Above, we use Effect to run when the page is loaded. Checking the state for validation. We can then also re run this Effect function when the dependencies passed into the array [enteredEmail] change.

Effect takes a clean up function also like so

useEffect(() => {
    console.log('effect running')

    return () => {
      console.log('effect running clean up')
    }
  },[enteredEmail])
Enter fullscreen mode Exit fullscreen mode

The return function that logs effect running clean up. Runs every time firstly before anything else inside the effect hook. Apart from the first time the function is called (page load).

Clean up can be used for example with a setTimeout function and clearTime out. To insure the Timeout is finished. Example of clean up...

  useEffect(() => {
    const identifier = setTimeout(() => {
      console.log('check validity!')
      setFormIsValid(
        enteredEmail.includes('@') && enteredPassword.trim().length > 6
      );
    }, 500)

    return () => {
      console.log('clean up')
      clearTimeout(identifier)
    }

  },[enteredEmail, enteredPassword])
Enter fullscreen mode Exit fullscreen mode

Discussion (0)