Better Programming

Advice for programmers.

Follow publication

Member-only story

React Context + TypeScript — The Easy Way

Spencer
Better Programming
Published in
5 min readNov 19, 2021
Image by author

The other day I was converting a JavaScript component to TypeScript and I got tripped up in one specific area: React Context.

Now don’t get me wrong, I’ve used TypeScript a million times before, but for some reason Context was not clicking with me. So I went back to the drawing board, looked up some tutorials, and familiarized myself with Context again.

That said, during this process I found some clean mental models and shortcuts that I found to make understanding React Context effortless.

That’s what I’m sharing here today.

The 3 Parts of React Context — Visualized

I like to think of Context as needing 3 parts. The official docs call these the createContext, producer, and consumer. But, I think it’s easier to think about these using the metaphor of just a normal variable.

The Context Creator

Think of this as the let myContext; of your Context. It’s just creating the Context, but not filling it with any functionality yet.

The Context Provider

Think of this as the myContext = []; of your Context. It fills the already created Context with some sensible default data.

The Context Consumer

Think of this as the myContext = [1,2,3]; or let myData = myContext[0] . This is where you will manipulate the Context or read its data (hence the name “consumer”).

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Spencer
Spencer

Written by Spencer

Software consultant for SaaS & Cross-platform | pwego.com

Responses (1)

Write a response