Answer the question
In order to leave comments, you need to log in
React, functional components, class components, hooks?
Hello.
I want to understand a few questions.
There is a component which is represented by a class.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler() {
// Тут делаем что-нибудь полезное
}
render() {
return (
<div>
<p>{this.props.children}</p>
<button type="button" onClick={this.clickHandler}>Click me</button>
</div>
);
}
}
function MyComponent(props) {
const clickHandler = () => {
// Тут делаем что-то полезное
};
return (
<div>
<p>{props.children}</p>
<button type="button" onClick={clickHandler}>Click me</button>
</div>
);
}
Answer the question
In order to leave comments, you need to log in
Hooks, in fact, solve only one problem - the problem of reusing the logic of the state of the components. If you don't need it use classes if you like them. In case you haven't seen good examples of using hooks, check out the possibilities of custom hooks.
useCallback prevents the child component from updating when a handler is passed to it. The call useCallback(fn, deps)
is equivalent to . Each time the parent component is updated without this wrapper, a new function reference would be returned and the child component would be updated. With useCallback , the old reference will be returned until at least one of the elements of the deps array changes. useMemo(() => fn, deps)
For the last 5 years, few people bother with speed / memory and create a bunch of extra callbacks both in classes and in functional components. Everyone is used to the fact that tabs in the browser gobble up a lot of resources and value the convenience / habits of the developer more than the speed and efficiency of the application. In many cases, this approach makes sense.
A class or a functional component is a matter of taste, development efficiency is the same, the difference in performance is minimal.
Hooks have just appeared, over time the practice of using them will be developed, problems will appear (if any), people will develop best practices and then it will be possible to say how much better it is than past approaches.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question