Summary of the Article
Have a project in mind?
Schedule a CallGetting started with React Hooks
Summary of the Article
React Hooks came into production with React v16.8 and it has completely changed the way we were thinking and using React. React Hooks enables us to build components using the functional approach instead of an object-oriented (classes) approach.
So the big question here is – What is React Hooks and why is everyone so excited about them. But before we discuss what React Hooks actually are, it is very important to understand the challenges that we are currently facing with React and how Hooks can help us solve these challenges.
For a deeper understanding, you can check out the official docs on React Hooks.
Challenges in React
Challenge 1 – Hard to reuse stateful logic between different components
In React, it is very hard to reuse stateful logic between different components. React does not offer a way to attach reusable behavior to a component.
So if you have worked with React, you do understand things like higher-order components or render props to help solve this issue.
But even using these patterns require you to refactor your component which is tricky and a little hard to follow. So all React needs is a better way to share stateful logic. This is where React Hooks come into place.
Challenge 2 – Complex components are harder to understand
Another challenge we were seeing in React is that complex components become hard to understand. Each lifecycle method often contains a mix of unrelated logic.
So mutually related code that gets split apart with these lifecycle methods whereas completely unrelated code ends up combined in a single method and this makes too easy to introduce bugs and inconsistencies.
In many cases, it is also not possible to break these components into smaller ones because the stateful logic is all over the place which makes it difficult to test them.
How React Hooks overcome the challenge in React?
With React Hooks, you can extract stateful logic from a component so that it can be tested independently and reused. Hooks allow you to reuse that stateful logic without any need of changing your component hierarchy and this makes easy to share React Hooks among different components.
React Hooks let you split your components into smaller functions based on which pieces are related rather than forcing a split on the lifecycle method.
So we can separate app concerns based on logic vs. which lifecycle method they belong to.
Let’s understand the basic syntax difference between React Class and React Hooks by building a simple temperature app.
Let’s see an illustration –
Simple temperature app using React class
So here, we have created a simple temperature app using React class components.
- We create a calculator class component with their initial state values in the constructor.
- We use different lifecycle methods –
- ‘componentDidMount’ – The method is invoked when the component is mounted.
- ‘componentDidUpdate’ – The method is invoked when the component props update.
- ‘componentWillUnmount’ – The method is invoked before the component is unmounted and destroyed.
- We use other calculator methods for various calculator operations.
- We use the TemperatureInput component that will render the input box and temperature values.
Simple temperature app using React Hooks
This renders the same thing as our React class. In React Hooks, we have our code based on what’s related vs. which lifecycle method they belong to.
So here, we have created the same temperature app using Hooks.
- We create a calculator functional component with their initial state values using setState Hook.
- We use the useEffect Hook. It will fetch the results from the weather API. Initially, the component will render and set the values with the help of setState Hook. We need to pass empty in the second argument to prevent running effect on each update. This work similar to componentDidMount. Then, we are returning a function that will work similarly to componentWillUnmount. We create another useEffect Hook that will run on every update similar to componentDidUpdate.
- We use other calculator methods for various calculator operations.
- We use the TemperatureInput functional component that will render the input box and temperature values.
What are React Hooks?
React Hooks are functions that give you React features like state and lifecycle methods without classes. React Hooks let you hook into React features.
Commonly used React Hooks
State Hook
We call it inside a function component to add some local state to it
import React, {useState } from ‘react’;
React will then preserve this state between re-renders. So you can use your functional component and add this State Hook.
Context Hook
It accepts a context object and returns the current context value for that context.
import React, { useContext } from ‘react’;
It lets you access the context and subscribe to it.
Effect Hook
It adds the ability to perform side effects from a function component.
import React, { useEffect } from ‘react’;
Custom Hooks
Custom Hooks let you create your own Hooks. A custom Hook is a JavaScript function whose name starts with “use” and that may call other Hooks inside of it.
When we want to share logic between two javaScript functions, we extract it to a third function. Both Hooks and Functional Components are functions so it works for them too.
Building a simple drag-drop app
Let’s build a very basic drag-drop app that demonstrates how to make reusable logic between the components and the difference between
- React Class Components
- Higher-Order Component
- React Hooks
Simple drag-drop app using React Class
Firstly, we will create a person and favorite component and call both files to index.js.
person.js using React Class components –
favorite.js using React Class components –
Simple drag-drop app using higher-order component
We will implement our logic in one file and use within both components.
person.js
favorite.js
And this is our higher-order component file that will perform a similar functionality between the components. Similar logic will work for both the components.
withContent.js
Simple drag-drop app using React Hooks
person.js
favorite.js
And this is our custom hook file that will perform the similar functionality of components.
useContent.js
Advantages of using React Hooks
- Hooks saves a lot of time as you have less code to write. It will be more beneficial when you are working on a medium-size app as it reduces the bytes from the bundle size.
- The code written in React Hooks is clean and neat and is very easy to understand.
- The code written in React Hooks delivers better performance.
- Logic is now shareable as React Hooks has decoupled the logic for state creation and how the state updates.
Final takeaways
- Only call React Hooks at the top level. It ensures that the Hooks are always called in the same order each time a component renders. It allows React to correctly preserve the state of React Hooks between multiple state Hook calls
- Only call React Hooks from React functions and custom Hooks. Don’t call them inside the loop, conditions, or nested functions.
- Make sure to put ‘use; in front of custom Hooks. This convention is very important and without it, we wouldn’t be able to automatically check for violation of rules because we couldn’t tell if your function has Hook calls inside of it.
- Backward-compatible. Classes can work side by side with React Hooks so you can uses classes and React Hooks in the same project.
Hire our experienced React developers
We are one of the leading ReactJS development company offering React development services for building interactive and light-weight applications using the toolchain and React API libraries.
Our experienced React developers offers custom ReactJS software development. Our developers offer enhancement over existing UIs and robust frontend driven by React.js technology.
Our React development team uses the latest, cutting-edge technologies. We offer an in-house QA team to ensure high-quality code by implementing UI testing, functional testing, etc.