0

How to set the state of parent component in react from inside child component? Child component is just a function where I want to set the state of the component.

Vishal G
  • 11
  • 1

1 Answers1

1

Pass the setstate into the child component and set the state there.

e.g.

const [user, setUser] = useState("")

childcomponentFunction(setUser) // function

In child component use like below

setUser(prev => ({
  ...prev,
  user: "testuser"
}))

The above will maintain the prev state as well set the state of parent.

Ajeet Shah
  • 15,652
  • 7
  • 55
  • 72