When to use private/protected methods in Typescript with React
Asked Answered
S

1

9

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.)?

Swithin answered 5/11, 2018 at 11:7 Comment(0)
R
13

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.

Readus answered 5/11, 2018 at 11:46 Comment(1)
Thanks for explaining this so well.Menzies

© 2022 - 2024 — McMap. All rights reserved.