How To Improve React Components With Optional Chaining
Let’s minimize errors in our web apps
3 min read
If you’re working on a big React (Next.js) application, sometimes you might need to dive deep into a data structure. It’s pretty generic. The React component I’m talking about would look like this:
If any property of
blok is missing, we have a big problem. The page will break and the user will get an error. 🥺 (see screenshot)
Improvement: Optional Chaining and Nullish Coalescing Operator
Optional chaining looks like this:
content?.content?.blok. The browser will first check if there is a
content property inside the
content object instead of assuming that this property exists. If it doesn't exist, it won't show an error but will make the variable
nullish. So it doesn't have a value.
Nullish coalescing operator
Now that our variable can be nullish, this means it can be
undefined. But we want to show both titles on the page instead of nothing.
The nullish coalescing operator looks like this:
??. It checks if the operator's left value is
undefined. If it is, you can give it a fallback value.
So it looks like this:
content?.content?.blok ?? 'Title'. If the value is nullish, it will assign the
'Title' to the variable. If the value isn't nullish, it will assign the title from the deeply nested object.
Improved React Component
If we implement the solutions we discussed before, our component looks like this:
Now, the user will always have a title and no errors. It’s better to be prepared for mistakes so that the user can continue their journey through the application.
Yes, the user will see a faulty title, but that’s far better than showing an actual error or, even worse, the page not showing!
Hopefully, this will help you improve your React components. Be prepared if the content doesn’t load or exist! And make sure the user has a great user experience.
I hope you learned something new or are inspired to create something new after reading this story! 🤗 If so, consider subscribing via email (scroll to the top of this page) or follow me here on Hashnode.
Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. 👍💰🎉🥳🔥
If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM's are always open 😁
Did you find this article valuable?
Support Dev By RayRay by becoming a sponsor. Any amount is appreciated!