Skip to content

Instantly share code, notes, and snippets.

@pflevy
Last active September 5, 2019 23:10
Show Gist options
  • Save pflevy/4f292936ff823cffc7447abdaa9aad0a to your computer and use it in GitHub Desktop.
Save pflevy/4f292936ff823cffc7447abdaa9aad0a to your computer and use it in GitHub Desktop.
Creating custom react hooks. Infinite scrolling example. Updated file using the custom hook.
import React, { useState, useEffect } from "react";
import { useInfiniteScroll } from "./useInfiniteScroll";
const App = () => {
// Assign the value returned by the custom hook to a variable
let infiniteScroll = useInfiniteScroll();
//Declaring the state
const [tableContent, setTableConent] = useState([]);
// useEffect with an empty dependecy array [] to run only once
// This works like componentDidMount()
useEffect(() => {
// Fetching fake data from an online API
fetch("https://jsonplaceholder.typicode.com/todos/")
.then(response => response.json())
.then(json => setTableConent(json));
}, []);
return (
<div style={{ textAlign: "center" }}>
<table>
<thead>
<tr>
<th>User ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{tableContent.slice(0, infiniteScroll).map(content => {
return (
<tr key={content.id}>
<td style={{ paddingTop: "10px" }}>{content.userId}</td>
<td style={{ paddingTop: "10px" }}>{content.title}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment