Skip to content
Discussion options

You must be logged in to vote

You're encountering unnecessary re-renders because the useEffect hook has data as a dependency. This means the effect runs every time data changes, which leads to a loop of fetching and setting state.

To fix this:

Remove data from the dependency array: This ensures the effect runs only once when the component mounts.

Use useRef to persist data across renders: This can help avoid unnecessary state updates.

Here's an updated version of your component:

import React, { useState, useEffect, useRef } from 'react';

const MyComponent = () => {
const [data, setData] = useState(null);
const hasFetched = useRef(false);

useEffect(() => {
if (!hasFetched.current) {
fetch('/api/data')
.then(response =>…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by elitedk52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Codespaces Your development environment, in the cloud. Run VS Code and code on GitHub's cloud platform, Question Ask and answer questions about GitHub features and usage
2 participants