DEV Community

Samiullah Khan
Samiullah Khan

Posted on • Originally published at technbuzz.com

1

Component Immutability and RequiredArray

While reading through component design, one of the recommended tip is to never mutate the input properties.

Let's look at the example below. (I am using Angular but same can apply to other frameworks)

@Component({...})
class MyComponent {
    @Input() status: Status[];
    get sortedStatus() {
        return this.status.sort();
    }
}
Enter fullscreen mode Exit fullscreen mode

Here sort is a mutable operation. This not only sort the array but also mutates the array.

I have prepared the stackblitz. Here we have status array of type string. It's passed down to child component. It's displayed both in parent and child component. In the child component I have a button Sort Array that basically sorts the status that is received via @Input().

Sort Array from child component sort array and it is reflected in parent component

Sort Array from child component sort array and it is reflected in parent component.

We can prevent this behavior by using the ReadonlyArray

The perks of using ReadonlyArray

This interface strips away all the mutable operations like push, pop, shift, unshift along with sort.

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up