I whipped up a quick React Context TypeScript example.
What is React Context?
React Context is a tool you can use to manage global state and functionality between unrelated components.
When would I want to use React Context?
For simple apps, it can be a replacement for more full-fledged state management solutions like Redux. For more complex apps, it can be used for other things like to share functionality via hooks. In more complex apps alongside Redux I've used it for localization, error logging, networking/API requests.
In my opinion, for apps that have more complex demands, it is not a replacement to Redux, it's a complement.
I would also strongly recommend using TypeScript for projects that use React Context. This is because it helps with readability. It requires developers to write more verbose code to support the default state, but in my opinion the pros outweigh the cons.
When would I not want to use React Context?
In larger apps with more complex state management requirements, React Context would not be a good choice for the following reasons:
- lack of tooling
Inter-dependence between resources
Often times in these apps, contexts are structured by resource, and sometimes these resources are inter-dependent, which means it has a strict nesting structure. If you ever find that resource A may need data from resource B, and that resource B could sometimes need data from resource A, you're gonna have a bad time. In more serious apps, I'd use Redux, but for simple apps with a limited amount of resources, I'd reach for React Context because it requires much less boilerplate than Redux.
Lack of tooling
Redux tooling is top notch. React Dev Tooling is pretty great too but for debugging state management bugs in complex apps, the Redux tooling is, in my opinion, superior.
React Context has some API's like
useReducer which essentially have you rewrite things that Redux would do for you, but in a way that's more confusing for everyone else on your team. In my experience, React apps that primarily use context can be more complex than ones that use Redux because the solutions end up being something that is specific to that developer and project and not something that can be easily looked up and discovered in existing documentation.
Gimme the codez
You can also see the embed below:
- React Context documentation
- Redux documentation
- React-Redux documentation -> React-friendly API's like hooks and providers.
- React dev tools -> must-have Chrome extension for React devs
- Redux dev tools -> must-have Chrome extension for projects using Redux
- React with TypeScript docs by React
- React with TypeScript docs by Microsoft
I'm techygrrrl and I stream gaming and coding on Twitch. Feel free to follow and I hope to catch you in one of my streams!