Getting Started with React Hooks
BLOG

Getting Started with React Hooks

author By Updesh Gandhi Feb 24, 2020
Submit guest post

Juggling through a widely cluttered line of code can be overwhelming, top it off with developing a specialized lightweight application and it may lead to unwelcome confusions. While working on a project, our team unanimously agreed on the need for a new component API that solved this problem at hand while remaining simple, flexible, and extendable. 

React Hooks was introduced to the project to write simplified functions without using classes, without calling super(props) and without worrying about binding methods by “this” keyword. 

In this blog, we will understand how React Hooks work and in what ways it can support your projects.

Understanding the Hooks

Components are building blocks of any React application. They are nothing but javascript classes or functions which optionally accept inputs i.e. properties (props) and returns a react element describing how a section of the user interface should appear. 

From React v0.14.0, we could create components in two ways - by classes or functions.

The difference lied on the component, if it had state or needed to utilize a lifecycle method (like componentDidMount, componentDidUpdate, componentWillUnmount) we had to use a class. Otherwise, if it just accepted props and rendered some UI, we could use a function.

At the beginning of 2019, the React new released version 16.8.0 that comes with the new addition which is a stable implementation of React Hooks. 

React Hooks are javascript functions which help you use state and other React features without writing a class and render prop pattern. It lets you extract component logic into reusable functions and replaces multiple lifecycle methods with simple hooks. It eliminates huge component problems which makes it hard to test and maintain.

Hooks cannot be called inside loops, conditions, or nested functions or from regular javascript functions. They can only be called at the top level from React function components.

Features of React Hooks

React Hooks is about improved and optimised code, reuse, and composition. Some of its features include: 

  • Optional opt-in
  • 100% backwards-compatible
  • Can be used in a component lifecycle without using a class
  • Let’s you collocate related logic in one place in your component
  • Share reusable behaviors independent of component implementations (like the render prop pattern).

How Does React Hook Deal with Other Components

Let’s dig deeper into how React Hook deals with other components such as state, lifecycle methods and non-visual logic.

  • State

Since we’re no longer using classes or this, we need a new way to add and manage state inside of our components. As of React v16.8.0, React gives us this new way via the useState method.

useState takes in a single argument, the initial value for the state. What it returns is an array with the first item being the piece of state and the second item being a function to update that state.grabbing each item in the array individually isn’t the best developer experience. This is just to demonstrate how useState returns an array. Typically, you’d use Array Destructuring to grab the values in one line.

  • Lifecycle Methods

With React Hook, you can think of the lifecycle methods in terms of synchronization.

While using these methods, whether to set the initial state of the component, fetch data, or update DOM - the goal is always to synchronize. 

When we think in terms of synchronization instead of lifecycle events, it allows us to group together related pieces of logic. To do this, React gives us another Hook called useEffect.

Defined, useEffect lets you perform side effects in function components. It takes two arguments, a function, and an optional array. The function defines which side effects to run and the (optional) array defines when to “re-sync” (or re-run) the effect.

 

  • Sharing non-visual logic

Because React couples UI to a component leading to over-complicated patterns like higher-order components or render props. 

However, with React Hooks, you can create your own custom Hooks that are decoupled from any UI.

You can consider using Hooks if your app is built on React 16.8 & up, consists of a single view, doesn’t save or load state, and has no asynchronous Input/Output. 

Here’re some predefined Hooks already in the latest release of React.

  • useState: This hook gave us the ability to manage state in functional component. It returns a stateful value, and a function to update it.
  • useEffect: This hook has been made for ‘side effects’, This function can be used in place of componentDidMount , componentDidUpdate , and componentWillUnmount of Class component.
  • useContext: That gave us the ability to pass data, config data in our app, down the components tree without using prop drilling.
  • useRef: Its returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.
  • useMemo: useMemo function first check if the dependencies have changed since the last render. If it's changed, then it executes the function and returns the result. If it doesn't change, then it simply returns the cached result. This optimization helps to avoid expensive calculations on every render.

Example of React Hook

In this example we are using a functional component named Example. Here we are using Hook useState to get & set state. In this example when you click on “Click me” button count will increment. This example code does not include class declaration, constructor, this binding etc.

The line : const [count, setCount] = useState(0); declares a state variable. The only argument to the useState()Hook is the initial state.

useState can be used more than once. It returns a pair of values: the current state and a function that updates it. This is why we write const [count, setCount] = useState(). This is similar to this.state.count and this.setState in a class. 

 

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. By the end of this blog, you should have a rough idea of what problems Hooks are solving. 

Discussion

Write to us

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms Of Service apply. By submitting this form, you agree to our Privacy Policy.

See how our uniquely collaborative work style, can help you redesign your business.

Contact us