Start Using ES2020 Features with React
One of the best things about working in Javascript is that we have access to newer features every year, thanks to the hard work of TC39 committee and developers who implement the spec. There are a number of changes in ES2020, but this article covers the ones that specifically improve the experience of building apps in React.
Optional Chaining
It’s a common pattern in React component libraries to pass down event handler props, such as onClick
or onChange
. When these props are optional, the child component will often have to check for the existence of each to avoid the dreaded undefined is not a function
error. Optional chaining helps provide a concise one-liner, which is useful for interactive components with lots of event handlers.
Note: You can also use it for nested object properties e.g. props.userInfo?.lastName
Null Coalescing Operator
Some components like controlled inputs often require deriving the value of state from multiple props. Prior to ES2020, a common way to have multiple fallbacks was using ternaries or ||
operators, which at times incorrectly led to omitting false-y…