Day 8:React Hooks (Part 2)
After a thorough introduction to React Hooks and the useState hook on day 7, we learned about the useEffect hook in React on the eighth day under the mentorship of Bikash Karki .
What is useEffect hook in React?
The useEffect in ReactJS is used to handle the side effects such as fetching data and updating DOM.
Why use useEffect hook?
useEffect hook is used to handle side effects in functional components, such as fetching data, updating the DOM, and setting up subscriptions or timers. It is used to mimic the lifecycle methods of class-based components. The motivation behind the introduction of useEffect Hook is to eliminate the side effects of using class-based components. For example, tasks like updating the DOM, fetching data from API end-points, and setting up subscriptions or timers, can lead to unwarranted side effects. Since the render method is too quick to produce a side-effect, we use life cycle methods to observe the side effects.
How does it work?
We call useEffect with a callback function that contains the side effect logic. By default, this function runs after every render of the component. We can optionally provide a dependency array as the second argument. The effect will only run again if any of the values in the dependency array change.
Importing useEffect hook
To import the useEffect hook, we write the following code at the top level of the component
import { useEffect } from "react"
Structure of useEffect hook
The useEffect hook syntax accepts two arguments where the second argument is optional.
//useEffect(callback/function, dependency)
useEffect(
() => {
// execute side effect (function)
},
// optional dependency array
[
// 0 or more entries
]
)
FUNCTION: contains the code to be executed when useEffect triggers.
领英推荐
DEPENDENCY: is an optional parameter, useEffect triggers when the given dependency is changed.
What is the useEffect cleanup function?
As the name implies, useEffect cleanup is a function in the useEffect Hook that allows us to tidy up our code before our component unmounts. When our code runs and reruns for every render, useEffect also cleans itself up using the cleanup function. The cleanup function is commonly used to cancel all active subscriptions and async requests.
useEffect(() => {
effect
return () => {
cleanup
}
}, [input])
Fetching Data from an API using Axios
Axios is a third library package that we can add to our program to retrieve information from an API. Because Axios is used in both web browsers and server-side JavaScript, it is useful for a wide range of tasks.
We install Axios package as follows:
npm i axios
Then, we import it in our project
import axios from 'axios'
In the following way, we can fetch the data from the API.
axios.get('https://example.com')
.then(response => {console.log(response.data)})
.catch(error => {console.log(error)})
Now, the data is ready to be used in various React components.