DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Taking advantage of react-router v6 to manage Providers
Daniel Kłys
Daniel Kłys

Posted on

Taking advantage of react-router v6 to manage Providers

All of us know how tricky may react architecture be. One of the best approach that I bumped into during my react developer career was to move files around until it feels right
and today I'd love to share my approach to setup <AppProviders /> with React Router v6

React Router provides us with powerful tool which is nested routes. Right now we may create routes in the following fashion:

export const Router = ({ providers }: { providers: React.ReactElement }) => (
      <Route path={AppRoute.home} element={providers}>
        <Route index element={<Home />} />
Enter fullscreen mode Exit fullscreen mode

and if our <AppProviders /> contains <Outlet/> inside, it will also render content of our subroute, in this case <Home />, as it is index ('/') of our precedent route.

So what we want to do is create our <AppProviders /> right now:

export const AppProviders = () => {
  const queryClient = new QueryClient();
  const theme = createTheme();

  return (
    <QueryClientProvider client={queryClient}>
      <CssBaseline />
      <ThemeProvider theme={theme}>
          <Outlet />
      {openReactQueryDevtools && <ReactQueryDevtools initialIsOpen={false} />}
Enter fullscreen mode Exit fullscreen mode

We could make more levels of routing to handle styles and <Layout /> appearance but in this simple scenario it's not necessary.

Then we could simply pass our <AppProviders /> as an prop to our Routing where we want to do it, for me it's index.ts

    <Router providers={<AppProviders />} />
Enter fullscreen mode Exit fullscreen mode

software architecture meme

Hopefully it could help any of you improving your react architecture-game.

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await