How To Properly Use React Context with TypeScript by Daniel K?ys
Tutorial by Daniel K?ys

How To Properly Use React Context with TypeScript by Daniel K?ys

While working with React and TypeScript, a problem that we often meet is the absence of the correct way to type our context. That may cause lots of errors in runtime, or in certain cases, what’s even worse – no errors when we need them ??.?

Inspired by one of his favorite e-books (TypeScript w React.js by Micha? Miszczyszyn ), Daniel K?ys , our Frontend Developer prepared a handy tutorial for those who deal with React Context in their daily tasks!?

So go through the possible ways to type Context in order to choose the best. For better understanding, follow up with Daniel’s tips below:

Example 1:?

Brak alternatywnego tekstu dla tego zdj?cia

Already at this stage, it starts to get complicated. What should be an argument for our context, when we don’t really want to evaluate it with any value from the very first? What we can do is mock empty values and provide them as an argument.

Example 2:

Brak alternatywnego tekstu dla tego zdj?cia

This way we can avoid errors regarding missing arguments, whilst evaluating our context. Though, It’s not the best way to do it. Putting aside the syntax and the fact, that this solution just doesn’t look good, the problem may be much bigger. When we don’t put real, expected values in our context, the app would work, but not as it would be expected to work. In a complex app that could take a while to find the source of the problem in logic.

The next approach that we may take is to assert type while trying to get data.

Example 3:

Brak alternatywnego tekstu dla tego zdj?cia

However, type assertion is never the best solution. It’s actually lying to the compiler that it will get something, that it actually may not get. As in the previous approach, this could lead to a bunch of bugs that we can’t really catch at the development level, due to putting down our environment.?

Example 4:?

Brak alternatywnego tekstu dla tego zdj?cia

So what is the best solution? Just create a hook responsible for communication with context! In the case of a missing provider, it will result in an adequate error.

This solution prevents the occurrence of unwanted errors, providing us with all the utilities of the TypeScript compiler. If we miss something - it will let us know!

要查看或添加评论,请登录

Digital Colliers的更多文章

社区洞察

其他会员也浏览了