Author:  React Hook – What it brings to the development?

Table of Contents

React Hooks were introduced at React conf oct, 2018as a way to use state and side effects in React function components. The React Hook APIs provide an alternative to writing class-based components and offer an alternative approach to state management and life cycle method.

Hooks are a new edition in React 16.8 that allows you to use state and other React features, like the lifecycle method without access to the class.  (React Hook brings you functional components, Hooks can do the thing once we are able to do with the class such as React local state, effect, and context has now done through useState, useEffect, useContext).

Important rules for Hook        

  1. Never call Hooks from inside a loop, condition or nested function
  2. Hooks should sit at the top-level of your component
  3. Only call Hooks from React functional components
  4. Never call a Hook from a regular function
  5. Hooks can call other Hooks

Type of React Hooks

useState: For managing local state

useEffect : Replaces lifecycle function

useContext: Allows easily work with React context API

useState

useState is the most used method. This is the replacement of this. state class components, using you can access the current state of a component instance, and initialize it with one single function call. When you call the useState function. It returns two items:

  1. state : the name of your state — such as this.state.name or this.state.location.
  2. setState : a function for setting a new value for your state. Similar to this.setState({name: newValue}).

The  values we initially set, get per component update, and set through events, always have the same type. With the provided typings, this works without any additional TypeScript:

// import useState next to FunctionComponent
import React, { FunctionComponent, useState } from 'react';

// our components props accept a number for the initial value
const Counter:FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
  // since we pass a number here, clicks is going to be a number.
  // setClicks is a function that accepts either a number or a function returning
  // a number
  const [clicks, setClicks] = useState(initial);
  return <>
    <p>Clicks: {clicks}</p>
    <button onClick={() => setClicks(clicks+1)}>+</button>
    <button onClick={() => setClicks(clicks-1)}>-</button>
  </>
}

useEffect

Most React components are required to perform a specific operations such as subscribing to a data stream, fetching data, manually changing the DOM. This kind of operation known as a side effect. Everything you would use component lifecycle methods for (componentDidUpdate, componentDidMount, componentwillunmount) The method signature is pretty straightforward.

In class-based components we put our side effects code into componentDidUpdate, componentDidMount. These are lifecycle methods that allow us to trigger the render method at the right time.

Here is a simple example:

useEffect(() => {
  const handler = () => {
    document.title = window.width;
  }
  window.addEventListener('resize', handler);

  // ⚡️ won't compile
  return true;

  // ✅  compiles
  return () => {
    window.removeEventListener('resize', handler);
  }
})

when you try making changes to the state values via the form, nothing happens. To fix this, you need to add another lifecycle method:

// Standard use case.
const [name, setName] = useState('Stefan');
useEffect(() => {
  document.title = `Hello ${name}`;
}, [name])

Updating the form should now update the document title as well.

useContext

useContext allows you to access context properties from anywhere in your components. It works the same as context.consumer class components.

import React, { useContext } from 'react';

// our context sets a property of type string
export const LanguageContext = React.createContext({ lang: 'en' });

const Display = () => {
  // lang will be of type string
  const { lang } = useContext(LanguageContext);
  return <>
    <p>Your selected language: {lang}</p>
  </>
}

Above mention Hooks are some basic React Hooks we also have additional React Hooks that you may need to use when it’s required.

  • useReducer: An advanced version of useState for managing complex state logic. It’s quite similar to Redux.
  • useCallback: Returns a function that returns a cacheable value. Useful for performance optimization if you want to prevent unnecessary re-renders when the input hasn’t changed.
  • useMemo: Returns a value from a memoized function. Similar to computed if you’re familiar with Vue.
  • useRef: Returns a mutable ref object that persists for the lifetime of the component.
  • useImperativeHandle: Customizes the instance value that’s exposed to parent components when using ref.
  • useLayoutEffect: Similar to useEffect, but fires synchronously after all DOM mutations.
  • useDebugValue: Displays a label for custom Hooks in React Developer Tools.

Advantage and Disadvantage of React Hooks

Now it’s time to see the Advantage and Disadvantages of these React Hooks.

Advantages:

  • Better alternative to the common design pattern.
  • Helps you to create more clear and concise code.
  • Easy to test and maintain (functional components).
  • Create re-usable, isolated components to avoid redundant logic.
  • Easy to use and write and co-locate.

Disadvantage:

  • Have to respect its rules, without a linter plugin, it is difficult to know which rule has been broken.
  • Need a considerable time practicing to use properly (Exp: useEffect).
  • Be aware of the wrong use (Exp: useCallback, use memos).

Conclusion

In summary, I can say React Hook is an interesting concept and responds positively by the developer community. Hook basically solve the very common problems, the everybody use Reacts come across, they encourage the use of functional components to benefit from its simplicity and efficiency. It has a predefined Hook as well as user can create a custom Hook.

For more articles –

Share this:
Share

Ankita Nathani

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Popular Products
Popular Posts
The Ultimate Managed Hosting Platform