Skip to content

Instantly share code, notes, and snippets.

@ravisiyer
Created February 12, 2024 10:30
Show Gist options
  • Save ravisiyer/249095329902bb715be2b7b8671d7669 to your computer and use it in GitHub Desktop.
Save ravisiyer/249095329902bb715be2b7b8671d7669 to your computer and use it in GitHub Desktop.
React custom hook state change causes linked component (App) re-render
import "./App.css";
import { useEffect, useState } from "react";
const useGetData = (dummyDataURL) => {
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = (url) => {
console.log("useGetData: useEffect: Just before calling setData()");
setData(["AE1", "AE2", "AE3", "AE4", "AE5"]);
};
fetchData(dummyDataURL);
setTimeout(() => {
console.log("After 2 second timeout");
fetchData(dummyDataURL);
}, 2000);
}, [dummyDataURL]);
return { data };
};
function App() {
const [posts, setPosts] = useState([]);
console.log("App: At beginning of App component");
// const { data } = useGetData("Dummy URL");
useGetData("Dummy URL");
return (
<div>
<h2>Testing App render when state of custom hook it uses, changes</h2>
<h3>Strict Mode commented out in index.js</h3>
<p>posts.length={posts.length}</p>
<p>{console.log("App: At close to end of App component render")}</p>
</div>
);
}
export default App;
Navigated to http://localhost:4001/
App.js:25 App: At beginning of App component
App.js:34 App: At close to end of App component render
App.js:9 useGetData: useEffect: Just before calling setData()
App.js:25 App: At beginning of App component
App.js:34 App: At close to end of App component render
App.js:14 After 2 second timeout
App.js:9 useGetData: useEffect: Just before calling setData()
App.js:25 App: At beginning of App component
App.js:34 App: At close to end of App component render
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment