React Provider Pattern

React Provider Pattern

So you don't pass props to grandchildren

So recently I've discovered this awesome website and after reading it all, I've discovered I could do some things better in my app.

Oh yeah, and by the way, I will start a new project at work with NextJs, NestJs and blockchain :D

In this episode I continue working on my Covid tracker in React and I've replaced the props with the provider pattern.

Basically, you create a react context in a parent component (in my case, it was the App component, since I'm using this data for all of the app) and then you can add data to this context which can later be used in grand children.

export const DataContext = createContext(null);

You wrap the children in this context provider and pass it a value (data in my case) just like you would pass props to a child.

<DataContext.Provider value={data}>
    <BrowserRouter>
        <Routes>
            <Route path="/" element={<Home />}>
            </Route>
        </Routes>
    </BrowserRouter>
 </DataContext.Provider>

Then, you can access this data in grand children components by importing the DataContext and using the useContext hook.

import { useContext } from "react";
import { DataContext } from '../../../App';

const data = useContext(DataContext);

Check out the full implementation in the video below

Find me on Twitter and the code on GitHub ;