DEV Community

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 }) => (
  <BrowserRouter>
    <Routes>
      <Route path={AppRoute.home} element={providers}>
        <Route index element={<Home />} />
      </Route>
    </Routes>
  </BrowserRouter>
);
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}>
        <Layout>
          <Outlet />
        </Layout>
      </ThemeProvider>
      {openReactQueryDevtools && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  );
};
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

ReactDOM.render(
  <React.StrictMode>
    <Router providers={<AppProviders />} />
  </React.StrictMode>,
  document.getElementById('root'),
);
Enter fullscreen mode Exit fullscreen mode

software architecture meme

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

Discussion (0)