Skip to content Skip to sidebar Skip to footer

Getting Error: Rendered Fewer Hooks Than Expected. When Using Usestate

I am using react-admin framework. I wrote my custom component that displays images in a materialUI GridList. I had to implement useState function to determine what elements to disp

Solution 1:

This article by Kent C Dodds might be related.

Can't be sure that this is your answer, without more details about how you are using the custom component outside - but looks like a violation of the following rules of hooks (quoted from the article)

you need to make sure that the hooks are always called the same number of times for a given component.

Paraphrasing the article, if you use a component as a function call, say something like this:

return arr.map(CustomComponent)

... since it's being called and not "rendered", the component's hooks are being interpreted in scope of the parent component - and it would it would translate to something like this...

constParentComponent() {
  return arr.map((item) => {
     // no. of hooks in ParentComponent depends on number of itemsconst [mouseOver, setMouseOver] = useState(false);
     .. rest of your component
   }
}   

...which violates the above rules of hooks mentioned.

Replacing that with this:

arr.map((item) =><CustomComponentitem={item}/>)

makes React interpret the hooks as part of the custom component scope, and it doesn't them throw this error.

Hope this helps!


Update

Adding the update here for posterity

The component in question did indeed have a function call like below:

{ids.map(id => GridTile({ id, record: data[id], basePath, classes, rowClick, getTileProps, resource }))}

Switching to rendering it fixed the issue:

{ids.map(id =><GridTileid={id}record={data[id] } basePath={basePath}classes={classes}rowClick={rowClick}getTileProps={getTileProps}resource={resource} /> )}

Post a Comment for "Getting Error: Rendered Fewer Hooks Than Expected. When Using Usestate"