loading...

React Hooks

danimal92 profile image Daniel Zaltsman ・2 min read

If you've been using functional components in your react project that contain a lot of logic and realized too late you need state, React Hooks is here to help!

In the early history of React, creating classes was a built-in method in React and at the time Javascript didn't have a way to natively build classes, until ES6. After ES6, React embraced classes in Javascript and made it so you can use native Javascript classes to create your components.

There were early problems with this, involving the complex nature of javascript classes like inheritance and the "this" keyword. In every class, because of ES6 standard, you had to remember to pass "props" to your super inside of your constructor method before you were able to use the "this" keyword.

On top of that, autobinding had to be done manually as opposed to the earlier "React.createClass()" method. For every method, you had to remember to bind each method to the object.

This quickly became a nuisance. Shortly after, thankfully, class fields were introduced which solved the problem of calling super. Additionally, using arrow functions solved the problem of autobinding.

This leads us to a question: why use function components?

Syntax friendly for javascript users

A function component is just a function. Easy to read and understand, there's no need to get confused with React syntax. It also inherently solved our previous issues with "super(props)" and the "this" keyword.

Lifecycle methods

Lifecycle methods are ways that classes manage application state. But with React Hooks, you can simplify the way your components maintain their internal state data, a la useEffect(). componentDidUpdate and componentDidMount can be reduced to one useEffect function. This was a problem since this logic is duplicated amongst those two methods, but with useEffect it is synchronized and only needs to be written once.

Sharing non-visual logic

React couples UI to a component, and the only way way to share logic between them was to use complicated patterns like Higher-order components and Render props. But React Hooks have an answer to that: custom hooks.

You can create custom hooks that are decoupled from any UI. As stated in the React documentation: "Unlike a React component, a custom Hook doesn’t need to have a specific signature. We can decide what it takes as arguments, and what, if anything, it should return. In other words, it’s just like a normal function. Its name should always start with use so that you can tell at a glance that the rules of Hooks apply to it...Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated."

Having hooks can make your future code simpler and highly reusable, so get out there and start experimenting with hooks!

Discussion

pic
Editor guide