i’m a rookie in react
the code is:
const Demo = () => {
const [current, setCurrent] = useState(0)
const add = () => {
console.log(current)
setCurrent(current + 1)
}
const Parent = (props) => {
return props.data.child
}
const Child = () => {
return (
<div onClick={() => {
add()
}}>Child</div>
)
}
// const data = {
// child: <Child></Child>
// }
const [data] = useState({
child: <Child></Child>
})
return (
<div>
<Parent data={data}>
</Parent>
</div>
)
}
Now the console out is 0 on every click, but when not using useState, the current will increace
I don’t know why, could any one explain for me, thank you so so much
2
Answers
I get it if use
Child is new, the
current
in add function closure is new on every render.but if use
Child is the same one in 2nd render, the
current
in add function closure is the same one, not the newcurrent
in 2nd render process.useState
only user for store data, not element. I see do you want to send data from Parent to Child. Try this!