Yan Skywalker
Yan Skywalker

Reputation: 119

react.js hook (too many re-renders)

I'm new to react.js hook. Not sure about why the following code doesn't work.

import React,{useEffect,useState} from "react"

function App() {

  const [fruit,setFruit] = useState("orange");
  setFruit("apple")      
  
  return (
    <div>
      <h1>{fruit}</h1>
    </div>
  );
}

export default App;

The error says that

Too many re-renders. React limits the number of renders to prevent an infinite loop.

Upvotes: 0

Views: 202

Answers (3)

Rashid Naveed CH
Rashid Naveed CH

Reputation: 31

The actual pattren of react is that when you set a state it cause rerender that means component re run again and recompile every line of code if it found a set state fucntion again it rerender and that's what happening in youe code. To prevent this you can use useEffect hook which accepts a callback function and a dependency array

For Example

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

The code in every useEffect will run with first time component mount and if you want to run the code again you need to pass dependency in 2nd argument of useEffect which decide that if the dependency change it's value the code in useEffect will run again.

In your case you can set state like this

useEffect(() => {
   setFruit("apple")
}, []);

Upvotes: 0

Mohamed Wagih
Mohamed Wagih

Reputation: 1466

You're setting the state inside the functional component body (The setFruit("apple") line) which will cause the component to re-render and when this happens all the component body will rerun again which will cause another set state call and so on which ultimately causes an infinite loop.

If you want to set the state when the component is mounting, You can use the useEffect hook to achieve that like so:

useEffect(() => {
  setFruit("apple")
}, []);

Read more about the hook here.

Upvotes: 2

Tomer Avraham
Tomer Avraham

Reputation: 74

you need to use useEffect

useEffect(() => {
 setFruit("apple") 
}, [])

Upvotes: 0

Related Questions