DEV Community

Cover image for useState && useEffect ⚛
Vipin Chandra
Vipin Chandra

Posted on

useState && useEffect ⚛

In Feb 2019 React hooks were introduced to react community
(React 16.8).
This new react feature solves one of the biggest problems faced by every react developers.

You can skip the problem section but it'll be good to know about what motivated React developers to bring hooks to the React.

Problems

  • Render props - Before Hooks, functional components were stateless due to which state needs to be passed to the functional component through props and if the application is too large then the drilling of props was one of the obstacle developers need to go through.
  • High order component - HOC wraps the component to give extra power like state but it also creates wrap hell as the application scale and application become too abstracted.

Let's explore Hooks now 💥

Hooks

Hooks is just a group of functions which Provide extra features to the Functional component by hooking to the core feature of react.

like State useState() , Lifecycle useEffect()

useState

useState() is a hook function which enable developers to use State in functional component.

import

import {useState} from 'react'
Enter fullscreen mode Exit fullscreen mode

usage of useState

const [stars , setStars] = useState(3)

Enter fullscreen mode Exit fullscreen mode
  • stars hold the initial value 3 is just like the state with the initial value.
  • setStars is the function which will set the stars like the this.setState.
  • useState receive initial value.

We can set multiple states variable by using useState again and again.

const [stars , setStars] = useState(3)
const [movie , setMovie] = useState("The martian")
const [userInfo , setUserInfo] =useState({
 userName:"john",
 email: "john@example.com"
})
Enter fullscreen mode Exit fullscreen mode

Example of useState

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [stars, setStars] = useState(3);
  return (
    <div className="App">
      <h1>Welcome to netflix </h1>
      <h2>The Martian</h2>
      <button onClick={() => setStars(stars + 1)}>Change Rating</button>
      <h1>{stars}</h1>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Output

Screenshot 2020-11-17 220149

Demo

setStars set the value of the star by incrementing one to the previous value. So every time you click the button the stars
increment.
Thus useState lets you to change and set state for functional component.

Every time we set a new state value the component rerender.

useEffect

useEffect() is a hook function which enable developers to use group of lifecycle method like
componentDidMount ( ) , componentDidUpdate( ) , componentWillUnmount() in functional component.

import

import {useState , useEffect } from 'react'
Enter fullscreen mode Exit fullscreen mode

useEffect runs after every render and most of the side effects (Like Network Request , subscription) are performed under this function.

useEffect(()=>{
// network requests
}  
 ,[ ])
Enter fullscreen mode Exit fullscreen mode

useEffect( ) has two parameters , function and Array variable.

  1. function contains the code which you want to execute after
    every render.

  2. Array contains a state variable names for which you want to run the useEffect.

Since the useEffect() functions are run on every subsequent re-render/update, we can tell React to skip a run, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for. React will only re-run the side effect if one of the items in this array changes.

Lot of English lets understand useEffect through code.

In this example, we will make a simple bookmark app.
This app will get a post from the API and the user can bookmark it.
Thats it! small app :).
Screenshot 2020-11-24 111709

Demo

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [post, setPost] = useState("");
  const [status, setStatus] = useState("Requesting....");
  const [display, setDisplay] = useState("none");

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then((response) => response.json())
      .then((json) => {
        setPost(json.title);
        setStatus("Recieved");
        setDisplay(" ");
      })
      .catch((err) => {
        setStatus("Error");
      });
  });
  return (
    <div className="App">
      <p>{status}</p>
      <p>{post}</p>
      <button style={{ display: `${display}` }}>BookMark</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Thats lot of code right ?

Lets understand this in pieces.

State part

we have 3 state variable in this small app

const [post, setPost] = useState("");
const [status, setStatus] = useState("Requesting....");
const [display, setDisplay] = useState("none");
Enter fullscreen mode Exit fullscreen mode
  • Post will be used to store the post received from api
  • status is basically used to keep track of the request status (Requesting or Received).
  • display will be used to toggle the display of bookmark button.

Jsx part

<div className="App">
      <p>{status}</p>
      <p>{post}</p>
      <button style={{ display: `${display}` }}>BookMark</button>
</div>
Enter fullscreen mode Exit fullscreen mode

status of request and post will be displayed on the page along with button.

useEffect part


useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => response.json())
      .then((json) => {
        setPost(json.title);
        setStatus("Recieved");
        setDisplay(" ");
      })
      .catch((err) => {
        setStatus("Error");
      });
  });

Enter fullscreen mode Exit fullscreen mode

As we know, use effect is basically used to perform side Effect (API request). So it's obvious that we will make our API request in the useEffect function.

  1. fetch will get the post for us from API
  2. As soon as we retrieve our post, setStatus will set the status to setStatus(received) and the display of our button will be toggled through setDisplay(" ").
  3. In any case, if we have any error in between the process the catch() will be executed further setting the status to Error;

Now our little useEffect application is complete.

I hope this article somehow helped you to understand the basic concepts of hooks 😄.
There's a lot more about hooks, so please go through the official react hooks docs too.

Top comments (0)