Creating a context with no default and no undefined check

 Creating a context with no default and no undefined check

This is the final post in a series of posts on React context with TypeScript. In the previous post, we consumed a context in a class component.

This is the final post in a series of posts on React context with TypeScript. In the previous post, we consumed a context in a class component. In this post, we will learn how to create a context without having to pass a default and then do any undefined checks when consuming it.

The problem

The type for createContext requires a default value to be passed into it, but often it doesn’t make sense to pass a default. So, we end up passing undefined as the default:

const ThemeContext = React.createContext<
  ThemeContextType | undefined
>(undefined);

… and then checking for undefined everywhere we consume it:

const { theme, setTheme } = useTheme()!;

A quick solution

A quick solution to the problem is to use the not-null assertion operator and remove undefined from the context type.

const ThemeContext = React.createContext<
  ThemeContextType
>(undefined!);

This works nicely because consuming code doesn’t need undefined checks. However, we are still passing a default.

react

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

How native is React Native? | React Native vs Native App Development

Article covers: How native is react native?, React Native vs (Ionic, Cordova), Similarities and difference between React Native and Native App Development.

What are hooks in React JS? - INFO AT ONE

In this article, you will learn what are hooks in React JS? and when to use react hooks? Also, we will see the react hooks example.

Build a simple React Native Pokemon app with React-Navigation

As we start learning new technologies we want to start building something or work on a simple project to get a better understanding of the technology.

Share Code Between React Native and React JS

React provides support for the server-side and frontend. Today, React development services are in demand as more and more organizations are considering software solutions that are crafted from the framework.

Validating React Forms With React-Hook-Form

In this article we will learn how to Validating React Forms With React-Hook-Form . Validating inputs is very often required. For example, when you want to make sure two passwords inputs are the same, an email input should in fact be an email or that the input is not too long