M
M
maxxim95952019-08-06 00:27:18
JavaScript
maxxim9595, 2019-08-06 00:27:18

How to declare components in React?

Practicing with React. As far as I know, there are three ways to create a React component:
- the usual declaration of the function ()
function - arrow functions
- creating a class
The class is needed for the component to have state (if not using hooks), if not - use arrow functions. On some sites they write that the class supposedly somehow has a bad effect on performance, and on others that there is no difference. So where is the truth? I understand that I'm just learning, but I would like to understand this ...
Another question, do I understand correctly that now there is a trend towards a complete rejection of class components in favor of hooks? Or is it just little things that are not worth attention ...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2019-08-06
@maxxim9595

Class components don't go anywhere. There are a few handy cases left for them. For example:
1. Convenient getting of previous values ​​of properties and states in componentDidUpdate.
2. Access to the component instance in handlers passed to browser APIs.
3. Complex components with many methods. For example videoplayer.
Performance may vary, but you and your users may not notice it. It should be understood that the initialization of hooks and the redefinition of all callbacks in functional components during redrawing is an operation that is more expensive than calling render on a class component in which all handlers are defined outside of render in the instance properties or in the prototype. Therefore, if a lot of things happen in the body of a functional component, then perhaps it should be rewritten into a class component, or, if possible, take out the logic from it, here custom hooks will help.
Optimization is a separate issue that is worth devoting time to. Now is it worth it to warn you that premature optimization is evil.
Try to use predominantly functional components and hooks in your code. Now almost all popular libraries have hooks that are quite easy to use in the API. Wherever you think it would be more convenient to use a class, don't be afraid to use classes.

P
Pavlo Ponomarenko, 2019-08-06
@TheShock

Sometimes classes are needed anyway. Therefore, in order for the code to be in the same style, I always use classes.

N
Newbie Ivanovich, 2019-08-06
@NovichokIvanovich

the same beginner as you and so far I use classes everywhere

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question