React Hooks: benefits with example

What is React Hooks?
React Hooks are functions.

React 16.8: Hooks were added as a new features in react version 16.8

Some popular built-in React Hooks
  1. useState
  2. useEffect
  3. useContext
  4. useReducer
  5. useCallback
  6. useMemo
  7. useRef
  8. useImperativeHandle
  9. useLayoutEffect
  10. useDebugValue
Benefits: Why we should use React Hooks?

Since we know there are maninly two reasons of using Class Components

  1. State Management
  2. Lifecycle Methods

So using React Hooks we can achieve similar functionality in a Functional Component.

Rules of using React Hooks

React Hooks has following rules:

  1. Always use Hooks at the top level of your React function components.
  2. Don’t call Hooks inside loops, conditions, or nested functions.
  3. Only Call Hooks from React function components not from regular JavaScript functions.
  4. Call Hooks from custom Hooks
React Hooks Example: useState and useEffect
import React, { useState, useEffect } from 'react';

function Example() {
    const [count, setCount] = useState(0);

    // Similar to componentDidMount and componentDidUpdate:
    useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
    });

    return (
    

You clicked {count} times

); }