Related Resources

Our Services

You May Also Like

What is Hook in React Js?

Shrijan Patel

Mar 13, 2023

7 min readLast Updated Mar 13, 2023

Hooks are special functions in React that allow functional components to have state and other React features. They were introduced in React version 16.8.0 and offer a more concise syntax and improved performance compared to class components. Built-in hooks, such as useState and useEffect, can be used to add functionality to functional components, enabling them to have the same capabilities as class components.

The most frequently used Hooks in ReactJS are:

useState: enables the addition of state to functional components.
useEffect: facilitates the execution of side effects in functional components.
useContext: grants access to the React context system.
useReducer: manages state through a reducer function.
useRef: provides access to the value of a DOM element or state from asynchronous        calls.
useMemo: returns a memorized value for improved performance.
useCallback: returns a memorized version of a callback function for optimized performance.

What is the common rule for defining hook in react js ?

The standard convention for defining Hooks in ReactJS is to start the name with the word use followed by a descriptive name that describes the purpose of the Hook. For instance, useState, useEffect, useContext, etc.

Additionally, it is critical to only invoke Hooks at the top-level of your components or within custom Hooks. Calling Hooks within loops, conditions, or nested functions can result in unpredictable behavior and should be avoided.

Let's begin to understand each hook in React one by one. This approach will help us to have a clear and thorough understanding of each hook, their use cases, and how they can be implemented in our code. By focusing on one hook at a time, we can ensure that we have a complete understanding of its functionality and how it can be used in our projects.

useState

The useState Hook in ReactJS enables the addition of state to functional components. State serves as a means of storing and managing data that may change within the component, making it vital for creating dynamic and interactive applications.  

Here's an example of utilizing the useState Hook:

import React, { useState } from 'react'

function Example() {
  const [count, setCount] = useState(0) // Declare a state variable "count" with an initial value of 0

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

export default Example

In this example, we declare a state variable count with an initial value of 0 using useState. We then utilize setCount to update the value of count when the button is clicked. Each time the button is clicked, the component re-renders and displays the updated value of count.

useEffect

The useEffect Hook in React allows you to synchronize your component with external systems. It acts as a way to inform React that your component requires certain actions to be performed after it has been rendered. useEffect is called within a functional component.

You can consider useEffect to be an integration of the lifecycle methods componentDidMount, componentDidUpdate, and componentWillUnmount from React Class components.  

useEffect takes two parameters - The first parameter takes function that encompasses the logic of any side-effects, and the second one an array of dependencies that determine when the effect should be executed. The effect will be re-run every time any of the dependencies change

Here's an example of using the useEffect Hook:

import React, { useState, useEffect } from 'react'

function Example() {
  const [count, setCount] = useState(0) // Declare a state variable named "count" with an initial value of 0

  // Declare a side effect that updates the document title whenever the count changes
  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>
  )
}

export default Example

This example demonstrates the utilization of useEffect to perform a side-effect of updating the document title in response to changes in the count state variable. The second argument passed to useEffect, the dependency array, informs React when the effect should be run. In this scenario, the effect should only be executed when the count value changes, so it is included in the dependency array.

Every time the button is clicked and the count state updates, the component will re-render, triggering the execution of the useEffect and updating the document title with the updated count value

useContext

The useContext hook in React is a powerful tool that enables functional components to access data stored in a shared context. The context is established using the React.createContext function, which creates a context object with a designated default value.

Here's an example that showcases the utilization of useContext:

import React, { createContext, useContext } from 'react'

const UserContext = createContext({ name: 'Guest' })

const UserDisplay = () => {
  const user = useContext(UserContext)
  return <div>{`Hello, ${user.name}`}</div>
}

const App = () => (
  <UserContext.Provider value={{ name: 'Thirdrocktechkno' }}>
    <UserDisplay />
  </UserContext.Provider>
)

In this example, we first create the context object UserContext using createContext. We then wrap our UserDisplay component in a UserContext.Provider component, which accepts a value prop. The value prop is set to an object containing the user's name.  

The UserDisplay component uses the useContext hook to retrieve the user data from the shared context. The hook takes the context object as its argument and returns its value.

As a result, the UserDisplay component will display Hello, Thirdrocktechkno.

useReducer

useReducer is a hook in React that enables you to manage state in your components. It offers a way to handle complex state transitions and is similar to using setState in a class component with added benefits.

The useReducer hook accepts two parameters: a reducer function and an initial state. The reducer function is a pure function that takes in the current state and an action, and returns the new state. The action is an object that describes the changes to be made to the state.

Let's take a look at an example to see how useReducer works in practice:

import React, { useReducer } from 'react'

const initialState = { count: 0 }

function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 }
    case 'DECREMENT':
      return { count: state.count - 1 }
    default:
      throw new Error()
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState)

  return (
    <div>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  )
}

In this example, useReducer is invoked with the reducer function and the initialState. It returns an array that consists of two elements, state and dispatch. state is the current state of the component and dispatch is a function that takes an action and updates the state. The component utilizes the state to render the count and the dispatch function to increment or decrement the count when the buttons are clicked.

useRef

useRef is a hook in React that provides a means to access and manipulate a DOM element. It's a convenient tool for retaining information that needs to persist across renderings of a component, such as the reference to an input field.

The hook returns an object with a single property, current, which is initially set to null but can hold any value that is required. This property remains unchanged across renderings, making useRef a reliable way to store information.

Consider the following example, which demonstrates how useRef can be used to focus an input field when a component is first mounted:

import React, { useRef, useEffect } from 'react'

function FocusableInput() {
  const inputRef = useRef(null)

  useEffect(() => {
    inputRef.current.focus()
  }, [])

  return <input ref={inputRef} />
}

In this example, the useRef hook creates a reference to the input field and stores it in the inputRef variable. The useEffect hook is then utilized to focus the input field when the component is mounted, with the ref prop connecting the inputRef to the input field and allowing it to be accessed in the useEffect hook.

useMemo

useMemo is a hook in React that optimizes component performance by memorizing the results of computationally expensive calculations. This helps to prevent unnecessary re-renders, as the hook will only recalculate the value when one of its dependencies changes.

The hook takes two arguments: a calculation function, and an array of dependencies. The calculation is performed only once during the initial render and its result is memorized for subsequent renders.  

Let's consider the following example, which demonstrates the use of useMemo to optimize the performance of a component that calculates the factorial of a number:

import React, { useMemo, useState } from 'react'

function Factorial({ number }) {
  const [value, setValue] = useState(number)

  const factorial = useMemo(() => {
    let result = 1;
      
    for (let i = 2; i <= value; i++) {
      result *= i
    }
      
    return result
  }, [value])

  return (
    <div>
      <input value={value} onChange={(e) => setValue(e.target.value)} />
      <p>Factorial: {factorial}</p>
    </div>
  )
}

In this example, useMemo is utilized to memorize the calculation of a factorial. The calculation is performed within the hook, and its result is stored in the factorial variable. Subsequently, the calculation is only redone if the number prop changes, which results in a much more efficient component.

useCallback

useCallback is a powerful hook in React that helps you to optimize the performance of your components. This hook works by memorizing the results of expensive functions, thereby avoiding unnecessary re-renders when the values of dependencies change.  

The hook takes two arguments: the first is the function to be memorized, and the second is an array of dependencies. The function will only be recreated if one of its dependencies changes, allowing you to optimize the performance of your component.  

Here's an example of how useCallback can be used to optimize the performance of a component that passes a callback function down to a child component:

import React, { useCallback, useState } from 'react'

const Child = ({ onClick }) => {
  return <button onClick={onClick}>Click Me</button>
}

const Parent = () => {
  const [count, setCount] = useState(0)

  const handleClick = useCallback(() => {
    setCount((prevCount) => prevCount + 1)
  }, [setCount])

  return (
    <div>
      <Child onClick={handleClick} />
      <p>Count: {count}</p>
    </div>
  )
}

In this example, useCallback is utilized to memoize the handleClick function. This function will only be recreated if the setCount function changes, resulting in improved performance and avoiding unnecessary re-renders of the child component.

Conclusion

In a nutshell, hooks in React are a game-changer for the performance and maintenance of your code. By offering a flexible approach, hooks allow you to incorporate state and additional features into your functional components with ease, resulting in more reusable and scalable code. The ability to encapsulate complex logic and reuse it across various components also helps optimize performance and avoids redundant re-renders.

Projects Completed till now.

Discover how we can help your business grow.

"Third Rock Techkno's work integrates complex frameworks and features to offer everything researchers need. They are open-minded and worked smoothly with the academic subject matter."

- Dr Daniel T. Michaels, NINS