Skip to content
Advertisement

Rendered more hooks than during the previous render REACT.js

I have an issue, I’m trying to set a value to a state (selectedPathway) regarding the another const (countryLabel) that is set via redux.

Once “selectedPatway” is set, I would like to display the result in <Select value={selectedPathway} /> This Select is return by the main component that surround all the logic.

Everything works well but when I refresh the page I get a “Rendered more hooks than during the previous render” in the browser. Here is the code:

 const DefaultValue = () => {
    let matchingOption = options.find((option) => option.value.includes(countryLabel))
    let optionSelected = options.find((option) => option.value === value)
  
    const [selectedPathway, changeSelectedPathway] = useState(matchingOption)
  
    useEffect(() => {
      let test = []
      if(matchingOption) {
        test = matchingOption
      } else {
        test = options[0]
      }
      changeSelectedPathway(test)
      
    },[countryLabel])

    useEffect(() => {
      changeSelectedPathway(optionSelected)
    },[value])

     return selectedPathway
  }

return (
   <Select
       value={DefaultValue()}
   />
)

I’ve looked all over the internet, and I think that I’ve applied everything correctly (well obviously not as it is not working…).

  • Not call hook conditionally
  • Use hook at top level

Any help would be very appreciated.

Advertisement

Answer

While not causing this explicit error, countryHasChanged and UsePrevious are both hooks (because they call other hooks), but not written as those. Hooks have to start with use with a lower-case u. Generally, I’d recommend you enable eslint and the the react hooks eslint rules (probably preconfigured if you are using create-react-app) since that extension will probably tell you about a ton of other hooks violation in your project and will finally also show you the place where your hook violation triggering this error originates from.

Also, give the Rules of Hooks documentation page a re-read.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement