How does Optional Chaining make React App development easier?

What do you do when you are not sure that the object variable has the specific property?

My recent answer is Optional chaining.

What is Optional chaining?

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

Optional chaining (?.) — JavaScript | MDN

I just quoted from MDN haha.

It basically makes it easier to access a property within an object.

How does it make React App development easier?

Imagine you fetch the user data from Firebase Authentication.

What’s gonna happen?

TypeError: Cannot read property 'dispayName' of null

Yes, this is what happens.

Conventional way

Trinomial calculus

I always used Trinomial calculus before Optional Chaining in this case.

In this pattern, your React app renders <div>Loading…</div> initially and then show <h1>Welcome, Your Name</h1> after fetching data from Firebase.

I kinda like this because <h1> doesn’t get rendered until it’s needed to be rendered.

Nullish coalescing Operator

Use Optional chaining

Just adding one ?! Deadly simple, isn’t it!?

Conclusion

I think most of the time Optional chaining is very handy and speeds up your development.

Count on Trinomial calculus when you need to show other elements while the object or property is not valid.

Trying to start a company in Vancouver https://taishikato.com