I am frontend developer in korea.
There is a problem that I am thinking about these days.
The questions are as follows :
I wonder if it is right to pass the setState function directly from the parent to the child. For an easy explanation, I'll attach an example.
// Example 1
const Parent = () => {
const [count, setCount] = useState(0);
return <Children setCount={setCount} count={count}/>
}
const Children = ({count, setCount}) => {
return <div onClick={()=> setCount(prev => prev + 1}>{count}</div>
}
// Example 2
const Parent = () => {
const [count, setCount] = useState(0);
const handleCount = () => setCount(prev => prev + 1);
return <Children handleCount={handleCount} count={count}/>
}
const Children = ({count, handleCount}) => {
return <div onClick={handleCount}>{count}</div>
}
Example 1 is handing over the setCount function that manages the count to the props to the child, and calling the setCount function from the child.
In Example 2, if you hand over the handleCount function that changes the state of the count to the props to the child, the child is calling the handleCount function.
As a result, I don't think it's good to hand over the setState function directly to the child (Example 1). The reason I think so is that parents should have the right to directly access the count, and the child should simply "call the handleCount function to change the count state" to the parent. In addition, while searching for the data, I saw the opinion that the relationship between parents and child components does not become independent if the setState is handed over to the child as props.