skip to Main Content

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


  1. 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:

    function Parent() {
     const [isOpen, setIsOpen] = useState(false);
    
     return (
        <>
          <button onClick={() => setIsOpen(true)}>Open Slider</button>
          <Slider isOpen={isOpen} setIsOpen={setIsOpen} />
        </>
     );
    }
    
    function Slider({ isOpen, setIsOpen }) {
     // Use isOpen and setIsOpen as needed within the Slider component
     return (
        // slider code
     );
    }
    
    Login or Signup to reply.
  2. If I answer your questions,

    Is it a good way to do it sharing a useState setter?

    -> Yes, unless causing rendering performance problem. If the render triggered by useState makes unnecessary renders in its children, you have to reconsider it.

    If yes how to send the setter from the child to the parent?

    -> 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search