Bytes

React JS Hooks: useState, useEffect, useRef and Custom Hooks

Last Updated: 18th October, 2023

React Hooks are functions that let you use state and other React features in functional components without writing a class component. Hooks were introduced in React version 16.8 as a way to simplify state management and reduce code duplication in React applications. They provide a more straightforward and cleaner way to manage the state, side-effects, and lifecycle methods of functional components. There are two types of hooks in React:

State Hooks: These hooks allow you to add state to a functional component. The most commonly used state hook is **useState** , which enables you to define state variables and their initial values.

Effect Hooks: These hooks allow you to perform side effects in functional components. The most commonly used effect hook is **useEffect** , which enables you to run some code after every render of the component, or after specific state or prop changes.

React also provides other built-in hooks like **useContext** , **useReducer** , **useCallback** , **useMemo** , **useRef** , and **useLayoutEffect** which allow you to manage different aspects of your component's behavior and state.

Advantages of using Hooks

The primary advantages of using React Hooks include:

  1. Simplicity and readability: Hooks simplify the logic of your code and make it easier to understand and follow. You can reuse stateful logic across components without introducing additional complexity.
  2. Code reuse: Hooks let you extract stateful logic from a component into a separate function, which can be reused across multiple components.
  3. Improved performance: Hooks can help improve the performance of your application by optimizing the rendering process and reducing the number of re-renders.
  4. Easier testing: Because Hooks extract stateful logic from a component, you can easily test that logic in isolation without having to render the entire component.

Working with useState

The **useState** hook allows functional components in React to have stateful logic, which was previously only possible with class components. Here's an example of how to use **useState**:

import React, { useState } from 'react';

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

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

In this example, **count** is a state variable, and **setCount** is the function used to update the state variable. The initial value of **count** is set to 0 using **useState(0)**.

When the button is clicked, the **setCount** function is called with the new value of **count** (in this case, **count + 1**). This triggers a re-render of the component, and the new value of **count** is displayed.

Overall, **useState** is a powerful and flexible hook in React that allows you to add stateful logic to your functional components.

Understanding useEffect

In React, the **useEffect** hook allows you to perform side effects in function components. Side effects are operations that interact with the outside world, such as fetching data from an API or updating the DOM.

The **useEffect** hook takes two arguments: a function that performs the side effect, and an optional array of dependencies that determine when the effect should be re-run. Here's an example of how to use **useEffect**:


import React, { 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>
  );
}

In this example, the **useEffect**hook is used to update the document title whenever the **count**state variable changes. The effect function sets the document title to **You clicked ${count} times.**

Working with useContext

In React, the **useContext** hook allows you to consume a context that has been created using the **createContext** function. Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Here's an example of how to use **useContext**:

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

const MyContext = createContext();

function Parent() {
  return (
    <MyContext.Provider value={{ message: 'Hello, world!' }}>
      <Child />
    </MyContext.Provider>
  );
}

function Child() {
  const { message } = useContext(MyContext);

  return <p>{message}</p>;
}

In this example, a context is created using the **createContext** function and assigned to the **MyContext** constant. The **Parent** component provides the context value using the **MyContext.Provider** component and the **Child** component consume the context value using the **useContext** hook.

The context value, **{ message: 'Hello, world!' }**, is passed to the **MyContext.Provider** component as its **value** prop. This value is then available to any descendant components that consume the context using **useContext**.

In the **Child** component, the **useContext** hook is used to retrieve the context value. The hook takes the **MyContext** constant as its argument and returns the context value, which is destructured to extract the **message** property. The **message** property is then rendered inside a **p** element.

Advanced Hooks

React provides a number of advanced hooks that can help you write more efficient and reusable code. Here are some of the most commonly used advanced hooks:

  1. useReducer: This hook is an alternative to useState and provides a way to manage complex state in your components. It works by dispatching actions to a reducer function, which then returns the new state based on the current state and the action.
  2. useCallback: This hook is used to memoize functions and optimize performance. It is useful when passing functions down to child components that may re-render frequently. By using useCallback, the function will only be re-created when its dependencies change.
  3. useMemo: This hook is similar to useCallback, but instead of memoizing a function, it memoizes a value. It is useful when performing expensive calculations that don't need to be re-computed on every render.
  4. useRef: This hook is used to create a mutable reference that persists across renders. It is useful for storing mutable values that don't affect the component's rendering, such as DOM elements or previous state values.
  5. useLayoutEffect: This hook is similar to useEffect, but it is synchronous and runs before the browser paints the screen. It is useful for manipulating the DOM or performing other imperative operations that need to happen before the user sees the updated UI.
  6. useImperativeHandle: This hook is used to expose a component's internal API to its parent component. It is useful when building reusable components that need to expose a specific API to their parent components.
  7. useContext: This hook is used to consume context that has been created using the createContext function. It allows you to access context values throughout your component tree without the need to pass props down manually at every level.

By using these advanced hooks, you can write more efficient and reusable code in your React applications.

Best Practices for Using React Hooks

Here are some best practices for using React hooks:

Only use hooks at the top level of a functional component. Don't use hooks inside loops, conditions, or nested functions.

Always call hooks in the same order. This helps to ensure that the state and effects are consistent across renders.

Don't call hooks conditionally. Hooks should always be called unconditionally at the top level of a component.

Avoid using too many useState hooks in a single component. Instead, use useReducer or useContext to manage more complex state.

Use useCallback and useMemo to memoize functions and values that don't need to be re-computed on every render.

By following these best practices, you can write cleaner, more efficient, and more maintainable React code using hooks.

Conclusion

React Hooks are a powerful tool that simplify state management, reduce code duplication, and improve the readability and performance of React applications. There are two types of hooks in React: State Hooks and Effect Hooks. The primary advantages of using Hooks include simplicity, code reuse, improved performance, and easier testing. The useState hook allows functional components to have stateful logic, while the useEffect hook allows performing side effects. useContext hook allows for the consumption of data through the component tree. Overall, Hooks provide a more straightforward and cleaner way to manage the state, side-effects, and lifecycle methods of functional components.

Module 3: Working with React ComponentsReact JS Hooks: useState, useEffect, useRef and Custom Hooks

Top Tutorials

Related Articles

  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter