React question detail
What is useEffect hook? How to fetch data with React Hooks?
The useEffect hook is a React Hook that lets you perform side effects in function components. Side effects are operations that interact with the outside world or system and aren't directly related to rendering UI — such as fetching data, setting up subscriptions, timers, manually manipulating the DOM, etc.
In function components, useEffect replaces the class component lifecycle methods(componentDidMount, componentDidUpdate and componentWillUnmount) with a single, unified API.
Syntax
useEffect(() => {
// Side effect logic here
return () => {
// Cleanup logic (optional)
};
}, [dependencies]);
This effect hook can be used to fetch data from an API and to set the data in the local state of the component with the useState hook’s update function.
Here is an example of fetching a list of ReactJS articles from an API using fetch.
import React from "react";
function App() {
const [data, setData] = React.useState({ hits: [] });
React.useEffect(() => {
fetch("http://hn.algolia.com/api/v1/search?query=react")
.then((response) => response.json())
.then((data) => setData(data));
}, []);
return (
<ul>
{data.hits.map((item) => (
<li key={item.objectID}>
</li>
))}
</ul>
);
}
export default App;
A popular way to simplify this is by using the library axios.
We provided an empty array as second argument to the useEffect hook to avoid activating it on component updates. This way, it only fetches on component mount.