I want to update state in Child ponent but it doesn't work. Actually, there're a lot of items. And I want to list each item with map
.
The error:
React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function ponent or a custom React Hook function
The code:
const renderItems = useCallback(() => {
return items.map((item, idx) => {
const { name } = room
const [isCopiedURL, setIsCopiedURL] = useState(false)
return (
<li key={idx}>
<CopyToClipboard
text={item.name}
onCopy={() => setIsCopiedURL(true)}
>
{item.name}
</CopyToClipboard>
</li>
)
})
}, [items])
I want to update state in Child ponent but it doesn't work. Actually, there're a lot of items. And I want to list each item with map
.
The error:
React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function ponent or a custom React Hook function
The code:
const renderItems = useCallback(() => {
return items.map((item, idx) => {
const { name } = room
const [isCopiedURL, setIsCopiedURL] = useState(false)
return (
<li key={idx}>
<CopyToClipboard
text={item.name}
onCopy={() => setIsCopiedURL(true)}
>
{item.name}
</CopyToClipboard>
</li>
)
})
}, [items])
Share
Improve this question
asked May 28, 2020 at 7:29
k10ak10a
1,0872 gold badges13 silver badges35 bronze badges
1 Answer
Reset to default 13You can convert the mapped return value to a ponent and then use useState
within it since hooks are meant to be used within functional ponents.
According to the rules of rules you can use them within functions such as map in your case
const Item = ({room, item}) => {
const { name } = room
const [isCopiedURL, setIsCopiedURL] = useState(false)
return (
<li key={idx}>
<CopyToClipboard
text={item.name}
onCopy={() => setIsCopiedURL(true)}
>
{item.name}
</CopyToClipboard>
</li>
)
}
...
const renderItems = useCallback(() => {
return items.map((item, idx) => {
return <Item room={room} item={item} key={idx} />
})
}, [items])
...