DEV Community

loading...

Handling side effects with useEffect()

idevbrandon profile image Brandon Ha ・1 min read

Working with (Side) Effects
Managing more complex state with Reducers
Managing App-wide or component-wide state with Context

Side Effects & intro useEffect
Main job : Render UI & React to User input

Side Effect : Anything else
Store data in brower storage
send Http request

useEffect(() => {...}, [dependencies])
1 arg : A function that should be executed AFTER every component evaluation IF the specified dependencies(2nd arg) changed

2 arg : Dependencies of this effect the function only runs if the dependencies changed

Using the useEffect() Hook
we could create infinite loop so that's why we need useEffect

useEffect(() => {
    const storedUserInfo = localStorage.getItem("isLoggedIn");

    if (storedUserInfo === "1") {
      setIsLoggedIn(true);
    }
  }, []); // run only once 
Enter fullscreen mode Exit fullscreen mode

data fetching is a side effect

useEffect() & Dependencies
Add function as a dependency
tell react that every login component function execution,
it will rerun this useEffect function if setFormIsValid, eventeredEmil, enteredPassword change.

  useEffect(() => {
    setFormIsValid(
      enteredEmail.includes("@") && enteredPassword.trim().length > 6
    );
  }, [enteredEmail, enteredPassword]);
Enter fullscreen mode Exit fullscreen mode

Whenever one of the dependencies change, useEffect() shines.
useEffect() has only one job to handle side effect

Using the useEffect clearnup function
A technique debouncing

return () => {}; // cleanup function

this run as a cleanup process before useEffect executes this function the next time.

It does not run before the very first side-effect execution.

Summary!
Every keystroke, effect will run every. useEffect() runs after every component render cycle.

with this function will only executes only once first time this component was mounted

we can add dependencies like enteredEmail, enteredPassed. this function will rerun whenever the component was re-evaluated and the state is changed

Discussion (0)

pic
Editor guide