Home > Software design >  react-native too many re-renders
react-native too many re-renders

Time:11-16

in my react-native code, this component is causing "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. This error is located at: in ArticleView (created by SceneView)"

Component:

import { exercisesList } from '-utils/exercisesList'
import { knowHowList } from '-utils/knowHowList'

import { useState } from 'react'
import { Text, View } from 'react-native'

const ArticleView = ({ route }) => {
  const [showList, setShowList] = useState([])
  const { itemId, currentList } = route.params

  if (currentList === 'exercisesList') {
    setShowList(exercisesList)
  }
  if (currentList === 'knowHowList') {
    setShowList(knowHowList)
  }

  const currentArticle = showList.filter((item) => item._id === itemId)
  
  return (
    <View>
      <Text>LIST:</Text>
      <Text>{currentArticle.title}</Text>
    </View>
  )
}

export default ArticleView

To the ArticleView component I am only passing an itemId and the currentList from which it is beeing called, so I can filter accordingly.

Can anyone see why is that happening? Thanks for the help!

CodePudding user response:

The reason is that you are calling your state setter immediately inside the function component body. To avoid this you can change your code as below.

import { exercisesList } from '-utils/exercisesList'
import { knowHowList } from '-utils/knowHowList'

import { useState } from 'react'
import { Text, View } from 'react-native'

const ArticleView = ({ route }) => {
  const { itemId, currentList } = route.params
  const [showList, setShowList] = useState(currentList === 'exercisesList' ? exercisesList : currentList === 'knowHowList' ? knowHowList : [])

  const currentArticle = showList.filter((item) => item._id === itemId)
  
  return (
    <View>
      <Text>LIST:</Text>
      <Text>{currentArticle.title}</Text>
    </View>
  )
}

export default ArticleView
  • Related