Use React Context API

===== Updated 20210910

Something like

  • We want to centralize the data at one place
  • We want to share data between components
  • We don't want to use Redux
  • We also don't want to pass the prop everywhere, from parent to children and from children to children's children
  • We definitely don't want to create the wrapper hell (something like a lot of HOC just for different level of consumers)

So we can use the useContext API

It's very easy:

1/ create a context with initial value (default state)

2/ export the context (so who wants to access to the data can import it)

3/ who wants to touch to the data should import the context object and use it

===== First version 20210905

We set up a bucket by calling React API createContext with some initial shit

export const ShitBucket = createContext(your-first-shit);

This guy returns us some things, including provider and consumer

interface Context<T> {
   Provider: Provider<T>;
   Consumer: Consumer<T>;
   displayName?: string;
createContext<T>(defaultValueState: T): Context<T>;

Then we use the provider as our shit provider, who wants to get the latest shit from him need to be rendered under this guys:

<ShitBucket.Provider value={latest-state}>

This provider doesn't have the shit himself, his children will contribute shit into the bucket via something like reducer & dispatch, but he can make sure that he's always able to give us the latest shit.

That's it!

And wherever the children want to get some shit from the provider, they can use the useContext, this hook requires the global bucket as a parameter:

const {shit} = useContext(OurGlobalBucket);