I am currently working on a React application with Typescript. When a component should provide a functionality with a ref a usually use a public method (public focus() : void {...}
), but I cannot decide when a component's method should be private and when protected.
I know that private and protected members are both accessible from the transpiled code, so the accessibility is basically the same during execution. So rather my question is: as best practice (wrt. a React component), which methods should be marked as private/protected and why(event handlers, custom handlers, component logic, etc.)?
Private - A private member cannot be accessed outside of its containing class. Private members can be accessed only within the class and even their sub-classes won't be allowed to use their private properties and attributes. Protected - A protected member cannot be accessed outside of its containing class.
protected implies that the method or property is accessible only internally within the class or any class that extends it but not externally. Finally, readonly will cause the TypeScript compiler to throw an error if the value of the property is changed after its initial assignment in the class constructor.
TypeScript provides three access modifiers to class properties and methods: private , protected , and public . The private modifier allows access within the same class. The protected modifier allows access within the same class and subclasses. The public modifier allows access from any location.
Private: These members are only accessible within the class that instantiated the object. Protected: This keyword allows a little more access than private members but a lot less than the public. A protected member is accessible within the class (similar to private) and any object that inherits from it.
This depends on developer's preferences.
All members that are supposed to be publicly available (including lifecycle hooks) can be made public
, e.g. a method that was designed to be called externally with React ref. The rest can be made protected
or private
, according to the principle of least privilege. This applies to any class, not just React. The choice may depend on whether a class is used internally or published as a part of the library, internal classes can be easily refactored according to current needs while overzealous encapsulation in a library will deprive a user of methods that a user could benefit in public API.
The use of private
prevents the class from being effectively extended. This may not a big problem in React because it promotes composition over inheritance principle.
A choice between private
and protected
is a matter of taste, basically a choice between meticulous encapsulation and preemptive extensibility. The use of protected
can be more justified because it provides practical benefits while drawbacks are rare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With