I am using a class inside my "useState" hook, and this class has a method to modify its content, here is a (quick) example :
class Test {
foo: string;
constructor() {
this.foo = 'foo';
}
modifyFoo() {
this.foo = 'bar';
}
}
.........
const [test, setTest] = useState(new Test());
test.modifyFoo();
.........
Is calling the method "modifyFoo" considered bad practice ?
I usually never modify an object without using setState, but in my personal case it is useful because I do not want to redeclare my class.
CodePudding user response:
Is calling the method "modifyFoo" considered bad practice ?
As always, it depends. But generally yes.
Think about what it would take to write React itself, put yourself in the shoes of the React team at Meta. For performance's sake you don't want to re-render if nothing has changed, but doing deep equality checks for reference types is expensive too and in the general case potentially ambiguous. So you compromise: you either check if the reference has changed (like in props) and/or you offer API hooks for the user to call to tell you something changed.
That is what the setter from useState
and the setState
method of class components is for: to tell React "hey I'm changing this thing, re-render the things that rely on it".
Because of the semantics, it is generally considered best practice to never mutate data that React relies on (i.e. data dependencies of your views).
React I believe gets its name in part from functional reactive programming, and even if I'm wrong about the origin of the name the design choices definitely resonate. Old-school OO code just isn't really a great fit and when dealing with third party APIs that are written that way (e.g. the Google Maps API) the generally accepted practice is to write functionalish Reacty wrappers for it.
So if you really don't want to change your class or new
up a fresh instance every time (and there are certainly cases where you wouldn't) you could always write React component wrappers for it rather than trying to use it directly.