I’m creating a React slider component. I would need to extract the setter that allowed the opening/closing of this slider to the parent.
I’ve got 2 questions:
- Is it a good way to do it sharing a useState setter?
- If yes how to send the setter from the child to the parent?
Here is an example of what I’m trying to do passing the setter to the parent to allow other component like a button to change the value of "isOpen".
function Parent() {
return (
<>
<button onclick={SetIsOpen(true)}/>
<Slider/>
</>
)
}
function Slider() {
[isOpen, SetIsOpen] = useState(false)
return (
// slider code
)
}
2
Answers
Yes, sharing a
useState
setter from a child component to a parent component is a common and effective way to allow the parent component to control the state of the child component. This pattern is useful when you want to trigger state changes in a child component from a parent component, such as opening or closing a slider.You can pass the setter function as a prop to the child component:
If I answer your questions,
-> Yes, unless causing rendering performance problem. If the render triggered by
useState
makes unnecessary renders in its children, you have to reconsider it.-> No. React implements One-way data flow which means child component can not lift props up to its parent.
Lastly, in your case, you should refer to Lifting state up written in React document.