Is it possible for me to get data that is fetched from a child component (via a graphql query) and use it in a parent component?
Example below where I need to use the data from React-component-4 in React-component-1. Is this possible or do I just need to do the fetch the data in React-component-1?
React-component-1 (need the data from component 4)
React-component-2
React-component-3
React-component-4 (graphql query for data)
React-component-5
React-component-6
3
Answers
You can use libs like Redux or Zustand(I really recommend) to share the data between components
Redux: https://redux.js.org]
Zustand: https://github.com/pmndrs/zustand
If a component needs some data, then it either fetch the data itself, or be passed that data from the parent (via passed props, or context).
So in your case,
React-component-1
should fetch the data and provide it toReact-component-4
.NOTE: Don’t do this
You can pass it back up with functions:
But this is a bad idea. It’s confusing and complicated. And as your app grows, tracking what data is coming from where will be very hard.
So the general rule is to put your state at the first common ancestor of the components that need that state. And then put your data fetching right along side it to populate that state.
If you want to do it without introducing 3rd party libraries there are two ways
Using Context API – https://react.dev/reference/react/useContext
Reverse Props – Passing a value from component 4 to 3 to 2 to 1 using reverse Props,
meaning you will pass a function in your child component from your parent component and when you call that function in your child component it will work in the parent component.
But this method is recommended if the hierarchy is only one level meaning only 1 child, but in your case, you have a long hierarchy,
so I recommend you to use React’s Context API as you dont want to use third-party libraries even though redux is great and far easy to use and manage then Context API.