50 Shades of React: useState & useEffect Edition

Context :

So, In this section of part of React We will deep-dive into useState hook and make a project around it. That can be To-Do app. We will see it further.


Content:

  • Hooks 101

  • State

  • useState hook

  • Making a counter

  • Event handling

  • TO-DO project

  • Component life cycle

  • Handling events with useState

  • use Effect in action

  • use case of use Effect


Pre-requisite:

Note : make written blog around all this . So you can refer this. If not all I would recommend my React basics ( at least see that).


Hooks 101 :

We have seen the various jargon in React Basics Component, Props.. etc.

The new Jargon We gonna see “ Hook “ —

  • Hook is a function , that is used in ( inside ) components. It hook into the components into various features like : State, Event , Event-Life cycle, context etc.

  • That is difference between Component and Hook. Components return JSX and Hook are used inside components.

  • Hook are used for to make the page Dynamic or We can say this add the functionality to the static Web page.

  • example : useState , useEffect ( main two hook without these We can't proceed in making the Websites ), useRef , useContext etc.


State :

So, useState hook works or manipulate the state. So, We need to understand :

What is State ?

  • State is the data or that thing of website that will change with time.

We will understand better when We gonna write useState.


useState hook :

So, The Question is Why in the first place We gonna use useState hook ? When We can do it with Bare JavaScript ?

If you think this maybe You should Watch this so in this section We gonna add two more section in this part only. That is :

  • Making a counter

  • Event handling

So, with this let’s start :

/src
  ├── App.jsx
  └── Hooks/
        ├── usestate/
                |--index.jsx

Counter app

  • Without Hook :

In Hooks/usestate/Index.jsx :

import React from 'react'
const learnedHook = "<h1>useState</h1>"

let counter = 0;
function Increment() {
  counter = counter + 1;
  console.log(counter)

}
export default function Index() {
  return (
    <div>
      {learnedHook}
      <h2>Conter app:</h2>
      <button onClick={Increment}>Increment</button>
      <h1>{counter}</h1>

    </div>
  )
}

and for App.jsx :

import React from 'react'
import Index from './Hooks/usestate/Index.jsx'

export default function App() {
  return (
    <>
      <>
        <Index />
        {/* from use state */}
      </>
    </>
  )
}

Output :

The problem with this JavaScript change the state the code in the section We want but this doesn't update the UI. That’s why We can't see it in the UI part.

That why we have introduced useState hook that will take care about the state of UI and render it on the Website.

  • here onClick is a event handler → That means When We click on something event will be handled or changed , When We click.

  • In a same way there is onChange event handler, We will see this in some time.


  • With the Hook ( useState )

syntax : useState →

const [parameter,setParameter]=useState(intial_value)

import React, { useState } from 'react'

export default function Index() {
  const [Counter, setCounter] = useState(0);
  function Increment() {
   setCounter(Counter + 1)
  }

  return (
    <div>
      <h1>useState Crash Course</h1>
      <h2>Conter app:</h2>
      <button onClick={Increment}>Increment</button>
      <h1>{Counter}</h1>

    </div>
  )
}

Output :

So, I hope you understand the useState hook. Now let’s make a project based upon it .

Let’s discuss it’s feature and Understand some more Concept about event handler and JavaScript Es6 things like ( spread operator and stuff ).

Project Todo : Blog link

So, In this next section We gonna understand about another hook. That is Event lifecycle and using use Effect hook.


Component life cycle and useState use case :

So , there is three part in Components they are :

  • Mounted :

when we see UI component on the website . the components is mounted

system for mounting component :

useEffect(()=>{
console.log(`it's monuting at ${counter}`)
},[])
  • Edited :

when We change the state of component and prop changes

We know that counter is the dependency for which the UI gonna change . That’s why It’s in the array.

useEffect(()=>{
    console.log(`mount is edited at ${counter}`)
},[counter])
  • Un Mounted :

when it’s re-render the website or remove the DOM from website.

For unmounting We must return thing. For Un mounting thing.

useEffect(()=>{
return () =>{
    console.log(`component is unmounted `)
}
},[])

Here is the Full code :→

import React, { useEffect, useState } from 'react'

export default function Counter() {
  const [counter, setCounter] = useState(0)

  useEffect(() => {
    console.log(`it is mounted`)
  }, [])
  // mounting it => without returning it

  useEffect(() => {
    console.log(`updated mount ${counter}`)
  }, [counter])

  // updated mount

  useEffect(() => {
    return () => {
      console.log(`clen up mounted done`)
    }
  }, [])

  function increment() {
    setCounter(counter+1)
  }
  return (
    <>
      <hr />
      <h1>counter:{counter}</h1>
      <button onClick={increment}>Increment</button>
    </>
  )
}

Here is the pictorial explanation :

Output


conclusion :

Okay, let’s be real. If you just stated react it’s bit tough for you but don't worry about it because when We are handling with notification, API calling.

Then We have to use useEffect hook for that purpose and even have to useState hook for some purpose.

In the next part We will see API calling there We will the effect of useEffect and useState .

Fetch API project : Click here


0
Subscribe to my newsletter

Read articles from the_OldSchool_coder directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

the_OldSchool_coder
the_OldSchool_coder

I am a passionate full-stack web developer with expertise in designing, developing, and maintaining scalable web applications. With a strong foundation in both front-end and back-end technologies, I specialize in creating dynamic user experiences and robust server-side solutions. Proficient in modern frameworks like React, Angular, Node.js, and Django, I thrive on crafting efficient, clean code and optimizing performance. Whether building RESTful APIs, designing responsive interfaces, or deploying applications to the cloud, I bring a results-driven approach to every project.Let me know if you'd like to customize it further, perhaps including your specialties or experience level!