Search code examples
reactjsreact-hooksrelayrelaymodern

Access PreloadedQuery's queryRef in a grandchild without passing down props


I am using Relay modern and I have preloaded query and I want to call the usePreloadedQuery hook in a grandchild/great-grandchild of the component where the query is initially loaded. In the documentation they are passing down the queryReference from the parent to the child. Is there a way to avoid having to pass down the queryReference through the entire parent child hierarchy?

I could possibly use React Context to do this but I am looking for a pure relay based solution.

Right now my only option is to use the useLazyLoadQuery hook in the grandchild component which is not ideal.

This is a related question Access Relay state without passing down props but even in the recommended approach we need to pass the fragmentRef down as props through the entire hierarchy.


Solution

  • Relay is built to work in tandem with React not replace it. I don't see any problem with passing a query reference through React context. Context is simply an implicit way of passing state to children that avoids prop drilling.