Use React without a Class
At React Conference 2018, Dan Abramov from the React team at Facebook introduced a new feature proposal(React Hooks) that lets you use state and other React features without writing a class. This has been released in in React v16.7.0-alpha and is being discussed in an open RFC. Before we get started, let us understand what React Hooks are:
Hook is a function provided by React to hook into React features like
state
andLifeCycle methods
from a function component.
This solves a wide variety of unconnected problems community has been facing in React with class components. Let’s quickly discuss a few:
- They have steep learning curve, as you need to understand complex JavaScript concepts to write
component
in a correct manner and build optimisations around them. - It is difficult even for compilers to optimise. The methods inside a minified component file is un-minified and unused methods are not stripped off as the compiler is not able to track usage inside classes.
- Maintenance of components that started out simple but grew into having a couple of logics in LifeCycle Methods. This led to having mutually related code that changes together gets split apart, but completely unrelated code ends up combined in a single method.
Furthermore, the community preferred writing stateful
component because we eventually end up converting function component to stateful
component.
Converting Class to Function Component
Let’s assume that we’re trying to write a Counter component, the normal implementation would be the following one:
The Hook based implementation would be the following one:
React exposes useState
hook that lets you add React state to function components. The only argument passed to useState
is the initial state.It returns a pair of values: the current state and a function that updates it.This is why we write const [count, setCount] = useState(0)
which is similar to this.state.count
and this.setState
in a class.
useState
is not the only hook React exposes, there a couple of others as well which I will be covering in my next blog along with how to share logics using hooks and write custom hooks.
If you want to go over my code to see how I have implemented the above code snippets, please visit demo.
Conclusion
Hooks represents React Team’s vision for the future of React along with how they are moving React forward so that newer patterns co-exist with the old ones so we can have gradual migration and adoption.
If you liked reading this, don’t forget to clap. 👏👏
You can also follow me on twitter @Akash940 for JavaScript or React updates.
Thank-you!