useEffect() into reactjs

To get rid of the negative impacts of employing class-based components, useEffect Hook was introduced. Examples of operations that can result in unwanted side effects include updating the DOM, obtaining data from API endpoints, setting up subscriptions or timers, etc.

One must employ life cycle methods to observe the side effects because the render method is too quick to develop them.To get rid of the negative impacts of employing class-based components, useEffect Hook was introduced. Examples of operations that can result in unwanted side effects include updating the DOM, obtaining data from API endpoints, setting up subscriptions or timers, etc. One must employ life cycle methods to observe the side effects because the render method is too quick to develop them.

In this article, we will learn about,

  • “Side Effects” & useEffect
  • Using the useEffect() Hook

Side effects and useEffect

Because they are activities taken in the “outside world,” side effects are unpredictable. When we need to act outside of our React components, we conduct a side effect. But performing a side effect won’t provide a predicted outcome.

Consider what would happen if we attempted to request data (such as blog entries) from a server that had malfunctioned and instead received a 500 status code response. With the exception of the most straightforward programs, almost all apps rely on side effects in one way or another to function.

UseEffect was created in order to handle performing these side effects in otherwise pure React components. When we incorporate elements from the Browser APIs, such as localStorage, into our React components, it has unintended consequences. This is known as React side-effects. Outside of the React scope,  denotes that something, like localStorage in the browser, is not a component of the React framework.

We produce side effects when we use React with any of the APIs provided by the browser, such as localStorage.

Using the useEffect() hook

  • Create an input form,

Below are the code snippets for the respective modules,

In the App.js file,

import React, { Fragment, useState } from "react";
import "./App.css";
import SimpleInputForm from "./components/SimpleInputForm";
const App = () => {
  return (
    <Fragment>
      <SimpleInputForm />
    </Fragment>
  );
};

export default App;

In the SimpleInputForm.js file,

import React, { useRef } from "react";

const SimpleInputForm = () => {
  // reference variable for name
  const enteredNameRef = useRef();
  // reference variable for email
  const enteredEmailRef = useRef();

  //   form handling function
  const handleFormSubmission = (e) => {
    e.preventDefault();
    const enteredName = e.target.name.value;
    const enteredEmail = e.target.email.value;
    console.log(enteredName, enteredEmail);
    if (enteredName && enteredEmail) {
      localStorage.setItem("isLoggedIn", "1");
    } else {
      alert("Please fill up all the input fields");
    }
  };

  return (
    <div className="w-2/3 mx-auto">
      <form onSubmit={handleFormSubmission} class="card-body my-20 p-0">
        <div className="form-control items-center lg:items-start">
          <input
            name="name"
            type="text"
            placeholder="user name"
            className="input input-bordered w-full max-w-md "
          />
        </div>
        <div className="form-control items-center lg:items-start">
          <input
            name="email"
            type="email"
            placeholder="email"
            className="input input-bordered w-full max-w-md "
          />
        </div>
        <div className="form-control items-center lg:items-start mt-6">
          <button type="submit" className="btn btn-sm w-full max-w-md">
            Register
          </button>
        </div>
      </form>
    </div>
  );
};

export default SimpleInputForm;

After running the server,

We will use localstorage primarily for storing user data.

  • Write the below code snippet inside of the handleFormSubmission function,
//   form handling function
 const handleFormSubmission = (e) => {
   e.preventDefault();
   if (enteredName && enteredEmail) {
     localStorage.setItem("isLoggedIn", "1");
   } else {
     alert("Please fill up all the input fields");
   }
 };

We are checking if the input fields are empty or not. If they are not empty, we are setting a value as isLoggedIn in the localstorage.

  • Go to app.js file and create state to hold user status there,
import React, { Fragment, useState } from "react";
import "./App.css";
import SimpleInputForm from "./components/SimpleInputForm";
const App = () => {
  const [isUser, setIsUser] = useState(false);
  return (
    <Fragment>
      <SimpleInputForm />
    </Fragment>
  );
};

export default App;
  • Add an h1 tag below of the SimpleInputForm component,
<Fragment>
  <SimpleInputForm />
  <h1 className="text-4xl">Welcome to home User</h1>
</Fragment>
  • Make this JSX conditional; such as, if the user data is stored in localstorage after clicking in the register button, the h1 tag will be visible. Else it won’t.
<Fragment>
  <SimpleInputForm />
  {isUser ? <h1 className="text-4xl">Welcome to home User</h1> : undefined}
</Fragment>

So, the flow is, after filling up all the input fields, a data will be stored in localstorage. And if the data is there, the h1 tag will be there. Else we will be seeing the input form. But we have to check the localstorage first with an if condition, whether the data is in localstorage or not.

  • Create an useEffect() hook with empty dependency and a callback function.
useEffect(() => {
  
}, []);
  • Write the if condition inside the callback function and check if the data is in the storage or not.
useEffect(() => {
  const storedUserData = localStorage.getItem("isLoggedIn");
  if (storedUserData) {
    setIsUser(true);
  }
}, []);

Now, why have we used useEffect here?…well, localstorage is not a part of react execution. It is a side effect here. If we were to write or set the state with setState outside the useEffect() and If there is user data present in the localstorage, it will set the data as true. And it will rerender the page again. Again it will see the data presents there and set it again. And it will continue doing it. Eventually, it will fall into an infinite loop. This is why we are setting the state value inside the useEffect hook here.

Let’s shorten the code a bit,

import React, { Fragment, useState } from "react";
import { useEffect } from "react";
import "./App.css";
import SimpleInputForm from "./components/SimpleInputForm";
const App = () => {
  const [isUser, setIsUser] = useState(false);

  useEffect(() => {
    const storedUserData = localStorage.getItem("isLoggedIn");
    if (storedUserData) {
      setIsUser(true);
    }
  }, []);
  return (
    <Fragment>
      {isUser ? (
        <h1 className="text-4xl">Welcome to home User</h1>
      ) : (
        <SimpleInputForm />
      )}
    </Fragment>
  );
};

export default App;

After filling up the input fields,

In the browser devtool,

And in the UI,