React

React Hooks

Hooks are new things Facebook added in React 16.8 which allow functional programmers to use even more features of React.


What are Hooks?

React Hooks are simple JavaScript functions that we can use to isolate the reusable part from a functional component.

Before React 16.8 Functional Components are only used to render stateless components, all stateful components must be defined using Class Components. Facebook has introduced React Hooks as a way to turn any Functional Components into stateful components.


Syntax

As a convention, a React Hook name needs to start with "use" and it must be a function. Check out some examples of React Hooks (useState, useEffect) below

import { useState, useEffect } from "react"

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

  useEffect(() => {
    document.title = `You clicked ${count} times`
  }, [count])

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  )
}

Built-in React Hooks

Below is the list of built-in and frequently used React Hooks that you need to know as a React developers


Rules of Hooks

Hooks are Javascript functions, but you need to follow two rules when using them. You can check out the Rules of Hooks from React for more information about why you should follow these rules.

Only Call Hooks at the Top Level

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Only Call Hooks from React Functions

Don’t call Hooks from regular JavaScript functions. Instead, you can:

  • ✅ Call Hooks from React functional components.
  • ✅ Call Hooks from custom Hooks
Previous
Introduction