How To Improve React Components With Optional Chaining
Let鈥檚 minimize errors in our web apps

If you鈥檙e working on a big React (Next.js) application, sometimes you might need to dive deep into a data structure. It鈥檚 pretty generic. The React component I鈥檓 talking about would look like this:
If any property of content or 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
We need two JavaScript features to prevent a massive error: optional chaining and the nullish coalescing operator. Don鈥檛 worry, this all sounds more complicated than it actually is.
Optional chaining
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 null or 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 null or 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鈥檚 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鈥檚 far better than showing an actual error or, even worse, the page not showing!
Conclusion
Hopefully, this will help you improve your React components. Be prepared if the content doesn鈥檛 load or exist! And make sure the user has a great user experience.
Thanks!
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 馃榿
About the author
馃殌 Tech Lead / Lead Developer 馃敟 Writing about CSS, JavaScript, Typescript, Angular, Vue.js, Nuxt.js, Serverless functions, and a lot more web-related topics. https://byrayray.dev/
Comments
Join the discussionNo comments yet. Be the first to comment.






