React UseEffect Hooks
UseEffect with infinite loop fix
export default function DataLoader() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data => setData(data));
}, []); // << When the array is empty, the effect runs only once.
return (
<div>
<ul>
{data.map(el => (
<li key={el.id}>{el.title}</li>
))}
</ul>
</div>
);
}
we can return a function to clean up the effect,
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("FromAPI", data => {
setResponse(data);
});
return () => socket.disconnect();
}, []);
render props with React hooks
import React, { useState, useEffect } from "react";
export default function DataLoader(props) {
const [data, setData] = useState([]);
useEffect(() => {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data => setData(data));
}, []); // << super important array
return props.render(data)
}
With a render prop we can easily share the data with child components:
export default class DataLoader extends Component {
state = { data: [] };
componentDidMount() {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data =>
this.setState(() => {
return { data };
})
);
}
render() {
return this.props.render(this.state.data);
}
}
<DataLoader
render={data => {
return (
<div>
<ul>
{data.map(el => (
<li key={el.id}>{el.title}</li>
))}
</ul>
</div>
);
}}
/>
Your first custom React hook
import { useState, useEffect } from "react";
export default function useFetch(url) {
const [data, setData] = useState([]);
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setData(data));
}, []);
(or)Using Async
useEffect(async () => {
const response = await fetch(url);
const data = await response.json();
setData(data);
}, []);
(or)
async function getData() {
const response = await fetch(url);
const data = await response.json();
setData(data);
}
useEffect(() => {
getData();
}, []);
return data;
}
import React from "react";
import useFetch from "./useFetch";
export default function DataLoader(props) {
const data = useFetch("http://localhost:3001/links/");
return (
<div>
<ul>
{data.map(el => (
<li key={el.id}>{el.title}</li>
))}
</ul>
</div>
);
}