DEV Community

Cover image for UseEffect hook in ReactJs with Typescript (Beginner)
Ayush
Ayush

Posted on

UseEffect hook in ReactJs with Typescript (Beginner)

Hello, FRIEDNZZZZZZZZZ......,
Sorry for the late, I haven't posted another blog in the last week. I'm here with the new topic useEffect() hook, How it works, and how we can use it in a proper manner. If you're ready then hit the like button with you BIG THUMB šŸ‘.

What is useEffect, that's the big question šŸ¤”.

useEffect is a React hook that allows you to perform side effects in your components. Side effects are any actions that interact with the outside world, such as fetching data, updating the DOM, or using timers.
useEffect takes two arguments: a function that contains the side effect logic, and an array of dependencies that controls when the effect runs. For example, if you want to fetch some data from an API when your component mounts, you can use useEffect like this:

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

above the code is a syntax, let's do the code and see how can we fetch the API data.

Get the data from API:

To do that we should import useEffect() into our component and if you're familiar with Json Placeholder, then use it as a fake API, But it actually provides a fake API for testing and for learning purposes.
that's the link for this fake API.

import { useEffect, useState } from 'react'

interface IDataModel {
  userId: number,
  id: number,
  body: string,
  title: string
}

export default function App() {
  const [data, setData] = useState<IDataModel[]>([])
  useEffect(() => {
    const GetPost = async () => {
      const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'GET',
        headers: {
          "Content-Type": "application/json"
        }
      })
      const json = await response.json() as IDataModel[]
      if (response.ok) setData(json)
    }
    GetPost()
  }, [data])
  return (
    <div className='row container-fluid py-3'>{
      data && data.map(post => <div className='col-lg-4 mb-3' key={post.id}>
        <div className="card">
          <div className="card-body">
            <div>Post number: {post.id}</div>
            <div className="card-title fs-4 fw-normal">{post.title.slice(0, 10)}</div>
            <div>{post.body.slice(0, 20)}</div>
          </div>
        </div>
      </div>)
    }</div>
  )
}

Enter fullscreen mode Exit fullscreen mode

In the above code, we saw that I use two hooks one is useState<IDataModel[]>([]) to get the response data and map those data into the JSX as you see. If you don't know about the useState<T>() hook then you should check my previous post.
In the useEffect(()=>{}, [data]) I pass the data into the array of dependencies because I want to run the useEffect when there are changes in the data variable. Now you got the point, useEffect works when a dependency changes its value.
And you'll get the result as shown below.

output
I use Bootstrap for UI in this ReactJs, If you don't know how to use the Bootstrap package in it, then check out my previous post, where you find out, How to install Bootstrap in ReactJs.
As you can see now the data from the API is fetched. You can also perform CRUD operation from your logic. You can also say that it's a Read operation from CRUD and in the next post, we'll perform other operations too.
Thanks for reading my blog and please also share with your Reactjs friends too, Namaste.

Top comments (0)