Will React Hooks Replace Classes? - reactjs

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.

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

Why create-react-app changed App.js component to function based component?

As I noticed, it seems create-react-app changed app.js class component based in a function component,
any idea why they did this?
React itself is moving away from class-based components.
A quotes from this doc: Introducing Hooks
In addition to making code reuse and code organization more difficult, we’ve found that classes can be a large barrier to learning React. You have to understand how this works in JavaScript, which is very different from how it works in most languages. You have to remember to bind the event handlers. Without unstable syntax proposals, the code is very verbose. People can understand props, state, and top-down data flow perfectly well but still struggle with classes. The distinction between function and class components in React and when to use each one leads to disagreements even between experienced React developers.
Additionally, React has been out for about five years, and we want to make sure it stays relevant in the next five years. As Svelte, Angular, Glimmer, and others show, ahead-of-time compilation of components has a lot of future potential. Especially if it’s not limited to templates. Recently, we’ve been experimenting with component folding using Prepack, and we’ve seen promising early results. However, we found that class components can encourage unintentional patterns that make these optimizations fall back to a slower path. Classes present issues for today’s tools, too. For example, classes don’t minify very well, and they make hot reloading flaky and unreliable. We want to present an API that makes it more likely for code to stay on the optimizable path.
To solve these problems, Hooks let you use more of React’s features without classes. Conceptually, React components have always been closer to functions. Hooks embrace functions, but without sacrificing the practical spirit of React. Hooks provide access to imperative escape hatches and don’t require you to learn complex functional or reactive programming techniques.

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.

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

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

Any new solution to replace redux in reactjs?

I am new with react js.
I made two components to send/receive data using props between them.
But it gets more complex, I feel like I need to replace them with other solution like redux. I wonder there is the latest better solution to replace redux now for communication between two react components.
There was a lot of opinions between redux and context api like this post. But today, I can say yes, you can replace redux with just react itself. Because, currently react provides so much concepts just like the redux, context api. You can find react additional hooks like useReducer, useCallback, useMemo, etc.
But arguably, redux is still worth for maintaining project easily. You can have redux devtool, keep the code clean (state in store - a separate place for concerns).
There are more concerns over this. You may see this issue what future react will have. You may also find the medium blog helpful and the reddit discussion.
Worth Reading:
State management with react hooks and context api
Redux main task is to be a 'predictable state container', and, as you wrote, it also makes sharing data between components much easier. The main drawback is that it requires additional code, but I think that it is worth it.
For apps / websites that are not very small, I wouldn't use react / react native without it.
The way redux works may be a bit difficult to understand in the beginning. The following is a great article that helped me when I started using it: redux connect explained

Resources