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.

The user variable will be like this after fetching data.

{ displayName: 'Mike' }
import React from 'react';
// Use Context API and make useStateValue
import { useStateValue } from './context/useStateValue'

function App() {
  const [user, dispatch] = useStateValue(null);

  return (
    <div className="App">
      <h1>Welcome, {user.dispayName}</h1>
    </div>
  );
}

export default App;

What’s gonna happen?

TypeError: Cannot read property 'dispayName' of null

error image

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.

{user ? <h1>Welcome, {user.dispayName}</h1> : <div>Loading…</div>}

Nullish coalescing Operator

<h1>Welcome, {user && user.dispayName}</h1>

Use Optional chaining

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

<h1>Welcome, {user?.dispayName}</h1>

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.