Skip to content

Instantly share code, notes, and snippets.

@paigen11
Last active February 6, 2021 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paigen11/b760039d92168515900cc62e9ba31536 to your computer and use it in GitHub Desktop.
Save paigen11/b760039d92168515900cc62e9ba31536 to your computer and use it in GitHub Desktop.
A sample of how to wrap the component providing the context values in a React application.
<CheckoutDrawerContext.Provider value={{ showDrawer, toggleCheckoutDrawer }}>
<section className="cart-checkout">
<CartDrawer selectedCartItems={selectedCartItems} />
</section>
</CheckoutDrawerContext.Provider>
@readikus
Copy link

readikus commented Feb 4, 2021

Hello, thank you for your post on this - it was very nicely written.

Quick question on this code - but I can't work out why you are putting showDrawer into the context, but then still passing it as a prop to the CartDrawer component.

Also, have you seen anyway of getting the state into the context? I just can't get passed the doSomething: () => {} that is in most context components. Seems bizarre to have to define a dummy function that is discarded.

@paigen11
Copy link
Author

paigen11 commented Feb 4, 2021

Hi, thanks for the your kind words.

You're absolutely right, I don't need to put showDrawer into the CartDrawer component - thank you for pointing that out - I will update it.

As for the dummy functions created in the Context file, you don't have to add them there if you don't want to. You could just create a context file with nothing in it besides instantiating the context, then wherever the provider is you can set all your state variables and functions you need the context to be responsible for in that component.

I like to be a little more explicit about what the context is responsible for, but there's no rule that it has to.

I hope this helps!

@readikus
Copy link

readikus commented Feb 6, 2021

Had a bit more reading around about the dummy function/values when the context is initialised, and I believe the rationale behind that is that state isn't guaranteed to be initialised, so the .Consumer part could/would end up with undefined values and functions.

Enjoyed learning context - thanks for the tutorial.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment