Dharmisha Doshi
Dharmisha Doshi

Reputation: 157

How can I stop React page to re-render?

I am using fetch to get data from API. I am using useEffect for page to stop rerender. But its not working

  const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }


  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };

  useEffect(() => {
     setLoad(false);
  }, [fetchPicth]);

Upvotes: 2

Views: 659

Answers (2)

Ashish Shah
Ashish Shah

Reputation: 1132

This can be solved using 2 approaches

  1. Pass state in dependency array of useEffect

const [picth, setPicth] = useState([]);   // Initial state

 useEffect(() => {
    if (picth && picth.length !== 0) {   // Checks if data exists and length 
                                         //is greater than 0
      setLoad(false);                    // Set Loading to false
    }
  }, [picth]);


const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
  };
  1. Check for the length, display Progress if there is no data. Display if data is present.

{picth.length === 0 && <div>Progress</div>}
      {picth.length > 0 && (
        <div>
          {picth.map((book, index) => {
            return (
              <YourComponent></YourComponent>
            );
          })}

Upvotes: 1

maxagno3
maxagno3

Reputation: 196

Remove the fetchPicth from the dependency array. If you'd like to set load to false you can do it like this:

const [load, setLoad] = useState(false);

 if (load) {
    return <h2>Progress</h2>;
  }


  const fetchPicth = async () => {
    setLoad(true);
    const response = await fetch(url);
    const data = await response.json();
    setPicth(data.pink);
    setLoad(false)
  };

  useEffect(() => {
     fetchPicth();
  }, []);

Using the code above will only fetch the data from the API only once i.e; when the component is mounted.

Upvotes: 0

Related Questions