Next.js Discord

Discord Forum

i want to send pata from child to parent without using useContext

Answered
Mahid posted this in #help-forum
Open in Discord
i have created a ecommerce store and i want to pass data from child to parents maybe using useState
Answered by New Guinea Singing Dog
Just pass the setter into the props of the child function
export function Parent() {
  const [num, setNum] = useState(0);
  return (
    <div>
      <p>{num}</p>
      <ChildComponent setter={setNum}/> 
    </div>
  )
}

function ChildComponent({setter}: {setter: Function}) {
    return (
      <button onClick={() => setter(x => x+1)}>Click here</button>
    )
  }
View full answer

5 Replies

New Guinea Singing Dog
You could create state and pass the setter to child
It's better to use state if it's about immediate parent .. if you are trying to pass multi-level parent/s then you should use context on top parent level [of the hierarchy you want the data to be available for].
@New Guinea Singing Dog You could create state and pass the setter to child
example please right now i am using useContext
@Mahid example please right now i am using useContext
New Guinea Singing Dog
Just pass the setter into the props of the child function
export function Parent() {
  const [num, setNum] = useState(0);
  return (
    <div>
      <p>{num}</p>
      <ChildComponent setter={setNum}/> 
    </div>
  )
}

function ChildComponent({setter}: {setter: Function}) {
    return (
      <button onClick={() => setter(x => x+1)}>Click here</button>
    )
  }
Answer