0
votes

I am new to React.

I have two functional components: parent and child. I need to access child state from parent but only when certain button in parent component is clicked. The child component maintains its own state using useState hook. I do not want to pass any callbacks from parent to child to avoid duplicating child state in the parent component.

I thought I can create a child ref in the parent use useRef hook and then access the child properties using ref.current but it seems not possible.

1
If you're not happy using callbacks (which sounds like it makes sense, tbh), the React convention would be to 'lift state up' (move the state to the parent), or alternatively use the more complex option of global-ish state with context sitting above both parent & child.jacobedawson
Data flow in react is from upward to downward direction, not the other way around like you want. You should move the state in parent component if parent component needs it and pass the relevant part of the state to the child componentYousaf
As I mentioned I do not want to maintain child state in the parent since I have many parents reusing the same child component. Moreover it seems very counter intuitive to common OO patterns: child should be encapsulated with its own state and parent should get child state via some sort of public methods when the parent needs to.user1744147
I found that if I convert the child functional component to the react class derived from React.Component then I can set a ref to this child component and call its bound methods or access its state directly via this ref. But it seems no way to do this if the child is functional component.user1744147

1 Answers

0
votes

you can not access the state of a component by its ref.
and I think there is no way to do so except passing a callback function to the child to sync states. but I recommend you to store the state in parent and change it there then pass it as prop to the child, it also prevents duplication of state.