React context with TypeScript
Our new hook accepts our contexts name for use in a thrown error message if its used outside of its provider. This is optional but will help with debugging the issue if you come across it. It then create a new context for us, passing in our generic or undefined. It then creates a new internal hook which runs the check for null or undefined for us by creating an additional context which is passed the parent functions context (the one we created first) and checking its value before returning it back. The parent function then returns a tuple with the inner hook and the parents contexts provider. Its set to const with a const assertion which sets the literals as readonly.
We can then use our new hook like so:
We have created an interface which will be passed to the context hook as its type, we are also passing in the name of our context as a string to be used in an error message if thrown. The naming of the context and the provider can be anything but the order of destructuring is important as they are returned as the context first, then the provider. Making sure to wrap whatever components are going to use our context somewhere in the component tree we can then use our new context hook like so: