React Tutorials
React ES6
React Hooks
Hooks are activities that can be reused.
If you have a component logic that needs to be used for multiple components, we can remove that concept from the Custom Hook.
Custom Hooks start with "use". Example: useFetch
.
In the following code, we download the data from our Home
section and display it.
We will use the JSONPlaceholder service to retrieve false data. This service is ready to test applications if no data is available.
To learn more, check out the JavaScript Fetch API section.
Use the JSONPlaceholder service to download fake "activity" items and display articles on the page:
index.js
:
import { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const Home = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch("https://jsonplaceholder.typicode.com/todos")
.then((res) => res.json())
.then((data) => setData(data));
}, []);
return (
<>
{data &&
data.map((item) => {
return <p key={item.id}>{item.title}</p>;
})}
</>
);
};
ReactDOM.render(<Home />, document.getElementById("root"));
Download logic may be needed in some areas as well, so we'll take that out of the custom Hook.
Submit download idea for new file to use as custom Hook:
useFetch.js
:
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data));
}, [url]);
return [data];
};
export default useFetch;
index.js
:
import ReactDOM from "react-dom";
import useFetch from "./useFetch";
const Home = () => {
const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");
return (
<>
{data &&
data.map((item) => {
return <p key={item.id}>{item.title}</p>;
})}
</>
);
};
ReactDOM.render(<Home />, document.getElementById("root"));
We have created a new file called useFetch.js
that contains a function called useFetch
that contains all the information needed to download our data.
We removed the URL with a strong code and replaced it with a url
variable that can be transferred to a custom Hook.
Finally, we return our data to our Hook.
At index.js
, we import our useFetch
Hook and use it like any other Hook. This is where we pass the URL to download data.
We may now use this Custom Hook in any section to retrieve data from any URL.