Converting my class-based component into functional components using hooks [duplicate] - reactjs

This question already has answers here:
React Function Components with hooks vs Class Components
(3 answers)
Closed 4 years ago.
I am new to Hooks, I really love the way hooks give us the ability to have state in a functional component using useState(), useEffects(), useReducer() etc, I also know it's always good to use a functional component where ever possible and limit the usage of class-based components at container level to hold the state of a root or a branch in component tree, it makes sure only a few components are managing our state and its easy to manage.
My Question: Why should I prefer to use hooks and not use a class-based component instead, what is the benefit of doing so?
I was planning to refactor my existing code base by converting many of my class-based component into functional components using hooks but I want to know whether it's worth doing so? the answers I get is gonna help me take a decision.
I am sure there is a benefit of doing so but not sure why not use class-based component instead?

My Question: Why should I prefer to use hooks and not use a class-based component instead, what is the benefit of doing so?
Mainly for:
readability/conciseness: most of the times you choose to use class-based components to do simple stuff (controlled input components, simple UI choices/options) and for doing that you usually
add some interaction (onCLick, onChange) handlers
add a constructor to bind them to the current component
and if you are implementing side-effects you start using the React lifecycle methods like componentDidMount, componentDidUnmount etc.
your component becomes more and more verbose just to do simple stuff.Hooks can help you to reduce this verbosity with a simpler to read, more concise and more readable component. The lines of code aren't 20%-50% dedicated to class structure anymore (definition, methods etc.) just to wrap your own code... but are ~100% your code directly.
simplicity: Hooks allow you to write super simple and atomic side effects/state logic that you can plug into your components in a while.
To add behaviors/features to super-simple components you don't need to transform them into classes, "force" yourself using one of the React patterns (Higher-Order Components, Render Props, etc.) that, especially at the beginning, make React so hard to get on board
stateful logic reuse: Hooks are so simple and connectable that you mix them and add rich/complex features without worrying about them (in fact Hooks can be consumed only in functional components and in... other Hooks themselves)
testability: that's an advanced concern but it could be important too. While Hooks mixes the presentation logic with the stateful ones (UI and state/side-effects aren't decoupled anymore), Hooks could be developed as super easy to be tested per-se functions (independently from you considering unit testing good or bad).
I was planning to refactor my existing code base by converting many of my class-based components into functional components using hooks but I want to know whether it's worth doing so? the answers I get is gonna help me take a decision.
Think twice before doing that, the docs themselves say
Try to resist adding abstraction too early.
and read the "useEffect is not componentDidMount + componentDidUpdate + componentWillUnmount" of the Kent post. There are some contraindications you must be aware before doing that.Instead: consider using Hooks for every future component instead of refactoring your old ones.
So make some checks and tests before doing that and refactor your component only when you master hooks 😉
p.s. I cited the HOC etc. React patterns: they remain valid and useful and with a lot of rooms for them, simply you won't find yourself using them for simple stuff that doesn't require them
p.p.s. if you are getting used to React Hooks you can find my memorandum useful, I wrote it for everyone that have already read the docs and sums up the most important Hooks stuff (linked to the docs etc.)

Related

React App with both Functional and Class components

I know that after the emergence of React Hooks, functional components are able to act almost the same as the class components, and I have seen lately an encouragement wave to use functional components.
My question is, could it hurt in any means to have a hybrid react app with some functional components and some class components? I understand that react would not complain about it, but I am looking for an experienced best practices, did inconsistency with component's types cause any problems?
Any tips are appreciated.
After sometime of using a hybrid project, I came to the conclusion that it is better to use functional components for the whole project. Not for any technical reason, but because of the community support.
Many of the packages today are made with functional components only (or mostly) in mind, having class components may require an additional workarounds to make it work.
Some packages creates a short-hand hooks for easier usage, eventually it becomes the official supported way for using the package, like what happened with react-alert.
Personally, I have function components that don't manage state and class components that do. However, this is not mandatory. With React hooks you can do everything with functions. It is your choice, it won't impact performance much. Functional components can be more performant when used right. Read more here

Is that safe to use functional components with hooks inside class based components in React?

I have a question regarding the React Hooks and class based components. I've heard from some developers that using functional components with React Hooks as a children of class based components may lead to some tricky bugs and that it's better to avoid doing so. I don't have more information about that and didn't find any articles or something like that.
So does anyone knows if it's true or not?
And if it's true please give me some examples or at least explain that to me.
I think the main reason of it is that we should stick with one style per project. I mean it is better to use only hooks (new projects) or only class components (for example in older projects) because doing 2 similar things in the same time will be hard for not experienced developers. But this is only my personal opinion.
Regarding your problem I think you have mistook it with this sentence "You can’t use Hooks inside of a class component". That means you can not apply hook to class component, but it is safe to render hook based component inside class.

Reactjs: What's best practice for working with class vs functional components?

So both class-based and functional components can work with state and lifecycle methods, if I am not mistaken. And that it is possible to structure your app with both or just functional components using hooks.
I was wondering if there are actually best practices in the real world. What approach is usually used in a corporate environment? Is there a definite answer to this or do companies combine all approaches constantly?
Using class components is "mildly discouraged". Which means writing new code mostly using function components (unless there are compelling reasons not to) and not spending any time/resourses on rewriting existing codebase to move from class components to their functional counterparts.
An example of a compelling reason to use class component would be the need to optimise the component that uses Redux (e.g. is connected to Redux store) for performance to the extent beyond what hooks allow.
Here we are changing all class components to functional components using hooks. Depending on component complexity we don't change for now.
But this is not a rule, actually, this is not recommended.
here is a React blog that covers this.

Are there still reasons to use class components if starting a hooks-enabled project?

I'm starting a new project that's based on React >16.8, where Hooks are now available and stable. I've played around with them and really like what they offer, and would like to adopt them as much as possible in my project. My question is.. how much? Is there any reason for them to not be 100%?
Since functional components are now offering the full arsenal of functionality that class components do, are faster, are much easier to write and much easier to read, are there still reasons to use class-based components?
At the time of writing this, there are only a few small edge cases not covered by functional components using hooks (see this FAQ) such as getSnapshotBeforeUpdate and componentDidCatch lifecycle methods. These are planned in a future hooks update.
Aside from those, every other feature of classical components can be rewritten in functional components that use hooks.
Classical components allow inheritance, but I personally don't consider component inheritance as part of the list of classical component features because it has been strongly advised against since the beginning of React, as it goes against the design pattern React was built to accomplish.
Overall, after a few more updates to the hook feature, all classical components will be entirely rewritable as functional components that use hooks.
You will need classes if you want inheritance, or want a component with common functionalities and extend it as needed. Other wise hooks provide a better and cleaner, easy to read, faster way to do almost all class functions.
Check this To-Do App with out using any classes.

Will React Hooks Replace Classes?

Now that React finally has hooks, will this eventually be the new standard for creating components or will the need to create class components still exist?
I understand that at the moment hooks can not accomplish everything a class can. Such as, providing hooks to lifecycle methods for getSnapshotBeforeUpdate and componentDidCatch. However, the React team has said they plan on adding this functionality soon. They also mention that there are no plans to remove classes from React.
So when all lifecycle methods are supported is there any reason to create class components? Do classes still handle certain situations better than a functional component at this point?
I'm going to politely disagree with the comments above. Hooks are 100% the future of React. I'd highly recommend reading the Medium article that Dan Abramov wrote in October 2018. There is also a video at the top of the article of Dan Abramov delivering the keynote address at the last React Conf. In his address he introduces hooks for the first time. He adds towards the end of address that he does not recommend refactoring your old components immediately, but he does recommend using hooks moving forward (and this is when hooks were still an alpha release):
I ask you not to rewrite your whole apps in hooks...because personally I find that it takes a bit of a mind shift to start thinking in hooks, and it might be a bit confusing if you just try to take a class Component and convert it, but I do encourage you to try using hooks in some of the newer code that you're writing and let us know what you think.
He follows that with:
So, in our view hooks represent our vision of the future of React. But, they also represent the way we move React forward, and that is that we don't do big re-writes. And, that is that we want the new patterns that we like better to co-exist with the old patterns.
He discusses this in greater detail if you watch the whole thing. I believe the take away from this is that Facebook and Dan Abramov see hooks as the future of React (so do I, but my opinion doesn't matter). They see the patterns that emerge from hooks as significantly better than the patterns established by class Components. They also indicate that the reason they intend to maintain class Components is because they don't intend to re-write React or introduce breaking changes.
There is also less code bloat due to the use of stateful functions as opposed to extending classes. Hooks hook directly into the global application state maintained by the React framework, as opposed to maintaining it locally through an abstraction (which is why they're called hooks). Hooks promote code re-usability through custom hooks. Hooks allow us to monitor individual state without lifecycle methods and conditionals through useEffect. There are plenty of other benefits to using hooks over class Components, but I don't want to write a book here.
In addition to the benefits listed, and the praise from the Facebook team, I'd point to all of the third-party libraries that are adding support for hooks. The FAQ page you shared indicates that both Redux and React Router are planning on releasing support for hooks. In fact, the Redux maintainers have been excitedly discussing hooks since they were introduced to the public. And, Ryan Florence (the creator of React Router) spoke after Dan Abrimov at React Conf. He actually gave a greater endorsement for hooks:
Dan just said "don't re-write your apps in hooks". I think you should.
In addition to those, Material-UI version 4-alpha is out, and they have introduced hooks as well.
In summary, hooks are the future of React, and we should be using them. They are in stable release since React v16.8.0, and there is no reason not to predominantly use them moving forward.

Resources