iCodeByte
iCodeByte

Reputation: 681

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

I'm writing a block of code to sort some data using React hooks. But I get the above mentions warning/error Below is my code.

const [sort, setSort] = useState(sortedInfo)

if (condition){
 // some logic
} else if (columns.find((col) => col.hasOwnProperty("actualSort"))){
 const {data, asc} = columns.find((col) => col.hasOwnProperty("actualSort").sorting)
 setSort(data);
}

My else case gets called many times which is fine as per the condition. Anything that can be done, so that setSort calls are minimized?

Upvotes: 3

Views: 464

Answers (3)

Robin Jiao
Robin Jiao

Reputation: 113

setState causes component re-render; and the re-render runs setState again - infinite loop; In Functional components, must use useEffect to fix this problem;

useEffect(() => {
   setSort(data)
}, [condition])

setSort() caused the re-render, and then (if the condition is not changed) useEffect() makes sure setSort(data) is not running again.

Upvotes: 1

Nagesh Sanika
Nagesh Sanika

Reputation: 1090

Calling setSort() in render triggers too many renders, use useEffect hook to trigger changes when value changes.

useEffect(() => {
  if (condition){
    // some logic
  } else if (columns.find((col) => col.hasOwnProperty("actualSort"))){
    const {data, asc} = columns.find((col) => col.hasOwnProperty("actualSort").sorting)
    setSort(data);
  }
}, [condition]); // Only re-run the effect if condition changes

Upvotes: 2

Viet Dinh
Viet Dinh

Reputation: 1951

setSort will call re-render. So, it call If condition. You should use logic of if condition in function call or useEffect.

Upvotes: 0

Related Questions