Home > Software engineering >  Is there a way I can get the state value stored within a Child's Child component to the Parent
Is there a way I can get the state value stored within a Child's Child component to the Parent

Time:12-16

I have a Parent Component - Within the Parent Component, I have a Child component called "Tabs". I use this "Tabs" component to call different tab child components. Now, within one of the child tab component, I'm setting some state values. Please see screenshot to understand how I've set this up. Let me know if you want me to setup a sample code in a sandbox.

I know we can do this with the first child by instantiating the state (get and set) in the parent and then passing this to the child where the child will set the value which can be retreived by the parent but i'm not sure in this scenario where i have a child's child component where i have the state value which i need at the main parent level)

Is there a way, I can access this state value which is within the Tab's Child component from the Parent Component ?

Additionally, can I access this state value within the other Tab Child Components ?

enter image description here

CodePudding user response:

I believe you have two options to solve this problem

  1. Lifting state up.

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor.

In your case, this means that you define the state at the parent level and then pass it on to all the children where it is needed.

  1. Context

You can define a state inside React.Context. In that way, you don't need to pass values to all three components; instead, you just get the state from the context. Additionally, context using helps to avoid props drilling problem

CodePudding user response:

In React manage the state globally to fix the problem, and you can use the state in any component, In React Redux play a major role in maintaining the state globally but it isn't very easy to understand, Here is the alternate package for maintaining state globally is zustand. Zustand is quite straight forward like managing hooks in our React.

Hope my answer helps to you, Thanks

  • Related