T
TanStack4mo ago
flat-fuchsia

expose route context select

Hi! I'm working on a big component and for perf reasons, I don't want to pass all recursive data top down but rather only the top data and each component is responsible for getting the right data:
<Example>
{ids.map(id => <ExampleGroup key={id} id={id} />)}
</Example>

function ExampleGroup({ id }) {
const group = useGroup(id)

// do stuff like rendering other example groups
}
<Example>
{ids.map(id => <ExampleGroup key={id} id={id} />)}
</Example>

function ExampleGroup({ id }) {
const group = useGroup(id)

// do stuff like rendering other example groups
}
Now, this is trivial to do with useRouteContext and select but I don't want to couple these components to the framework. That did sound like a good usecase for dependency injection via react context:
// React Context Provider under the hood
<Example
select={(cb) =>
Route.useRouteContext({
select: (context) => cb(context),
})
}
>
{/* */}
</Example>
// React Context Provider under the hood
<Example
select={(cb) =>
Route.useRouteContext({
select: (context) => cb(context),
})
}
>
{/* */}
</Example>
But this doesn't respect the rule of hooks, although it works. Did anyone try a similar thing before, and how did you do it? Thanks!
2 Replies
helpful-purple
helpful-purple4mo ago
i dont think there is a way to do this without using the framework funcions inside the component, if you dont want to mix the logic, you can create a wrapper component that uses the framework functions and just pass the data from it to the actual component?
flat-fuchsia
flat-fuchsiaOP4mo ago
Yeah I may do that thanks! I'm doing https://zustand.docs.pmnd.rs/hooks/use-store-with-equality-fn, and I pass data from the router context

Did you find this page helpful?