Page Content

Tutorials

Understanding The React Hooks With Code Example

React Hooks 

With the release of version 16.8, React Hooks  a noteworthy addition to the React library completely altered the way that state and other React capabilities can be used in functional components. Class components were largely the only ones with these capabilities before React Hooks. By allowing developers to “hook into” React features like state and lifecycle methods straight from functional components, hooks basically, regular JavaScript functions allow developers to create dynamic and interactive user interfaces without having to construct classes.

React Hooks 
React Hooks 

The Reasons and Objectives of React Hooks

React app hooks were implemented to solve frequent issues and improve developer experience for numerous reasons:

Avoiding Class Components for State and Lifecycle Management: Before Hooks, a component had to be a class component to use lifecycle methods like componentDidMount for data fetching or keep its own state. Because applications used functional and class components, the codebase was sometimes inconsistent and harder to redesign.React Hooks let functional components follow lifecycle events and have state, making them as powerful as class components in most cases.

Shorter, More Readable Code:Functional components, especially those improved with React Hooks, are shorter and easier to understand than class-based equivalents. By eliminating class boilerplate, keyword binding, and unique lifecycle routines, they simplify programming.

Enhanced Logic Reusability: Hooks let you encapsulate and reuse stateful functionality across multiple components without using HOCs or render props for every circumstance. This reduces code duplication and improves organisation.

Solving Complex Data Flow Issues: Hooks make it easier to manage component logic, which could otherwise result in “prop drilling” or “wrapper hell” (passing props down through several levels of components).

Although the official React documentation encourages the use of React Hooks for managing state with functional components when writing new code, class components are still supported and crucial for comprehending legacy code and for specific features like componentDidCatch (which is not available in Hooks).

Key Built-in Hooks

React offers a collection of pre-built Hooks that address the most popular scenarios for incorporating side effects and state into functional components. All React Hooks begin with the word “use,” as is customary.

You can use dynamic values in place of the hard-coded data now that you have a functional component. You can import any of the Hooks that React exports straight from the main React package. React Hooks, like useState, useContext, and useReducer, typically begin with the word “use.”

UseState()

Purpose: Adding state to functional components is made possible by this hook. You can divide state into several separate, independently updateable components with useState, as opposed to class components, which have a single state object.

Signature: useState() returns a two-item array with the starting state as its single input.

  • The state variable’s current value appears as the array’s first entry.
  • To change that state, the second item is a function (like this.setState in class components) that, when called, will cause the component to be re-render.

Usage: You can designate any variable names you like to receive the returned values by using array destructuring. UseState lets you set a value without referencing the current state. UseState(0); const [count, setCount]. For consistency, state variables must be established at the start of your functional component, never inside loops, nested functions, etc.

UseEffect()

Purpose: A functional component’s “side effects” are handled by this hook. Side effects are actions that have an impact on the component’s “outside world” and include:

  • Explicitly changing the DOM (for example, by adding a document title). Eliminating the negative impacts of employing class-based components is the driving force for the launch of useEffect.
  • Pulling information from APIs. A React class’s state is a unique property that governs how a page is rendered.
  • Configuring timers or subscriptions. To record events that take place outside of the current component, you will need to add global event listeners to the Window object in the following step.
  • Event listeners can be added or removed. This stage involves displaying user information in a pop-up component that activates when the user focusses on an input and closes when they click elsewhere on the page.

Signature: useEffect() takes an optional list of “dependencies” as its second argument and a function (the “effect” function) as its first argument.

Default Behavior (no dependency array): The effect function is executed following each component render in the default behaviour (no dependency array).

Empty Dependency Array ([]): The effect function only executes once following the first render (and cleanup runs on unmount) when the Dependency Array is empty ([]). This is frequently used to retrieve data that is constant.

Non-empty Dependency Array ([prop1, state2]): The effect function is executed following the first render and only when any of the values in the dependency array are altered.

Cleanup: A cleanup function may be returned by the effect function voluntarily. Before the effect recurs because of dependency changes or before the component unmounts, this cleanup operation will be carried out. To stop memory leaks, such as when event listeners are removed or API calls are cancelled, this is essential.

UseContext()

Purpose: Functions can subscribe to React Context with the help of this hook. Passing data across the component tree without manually passing props down at each level (a process called “prop drilling”) is made possible by context. Across numerous components, it is perfect for sharing “global” data, such as theme settings or user authentication status.

Usage: It uses a Context object that was made with React.returns the current context value when createContext() is used as an argument. Use JSX to render UserContext. The information you supplied in the value prop will be returned by the hook. The information should be saved to a new variable named user, which is an object with a name and preferences. After that, you can use user.name in place of the hard-coded name.

UseReducer()

Purpose: This hook manages more complex state logic than useState, especially when state changes involve many sub-values or the current state depends on the preceding state. The concept is identical to Array.prototype.reduce(). The useState React Hooks are useful for setting values without referring the current state.Reducer Hook helps you reference a prior value or perform complicated data changes.

You’ll develop a product page component with a shopping cart and update it by adding purchases from a list to test these state settings. After this training, you’ll be comfortable utilising React Hooks to manage state in a functional component and build a basis for useEffect, useMemo, and useContext.

Signature: Using a signatureReturning the current state and a dispatch function, Reducer() accepts two arguments: a reducer function and an initialState. State updates are initiated by passing “actions” to the reducer via the dispatch function.

UseMemo() and UseCallback()

Purpose: By memoizing values and functions, respectively, these react hooks serve as performance optimisation tools that save needless recalculations or re-creations when components are re-rendered. Utilise Reducer React Hooks as well. When setting a value without consulting the use’s existing state, the useState Hook is useful.When you have many actions that call for intricate data manipulations or when you need to refer to a previous value, Reducer Hook can be helpful.

useMemo(): The function useMemo() caches the outcome of a calculation. Only in the event that its dependencies alter does it recalculate the value. This step involved memorising component portions. You used the useMemo Hook to exclude an expensive function from the rest of the component and only run it when specific dependencies change. Next, memoize routines to avoid shallow comparison re-renders.

useCallback(): Caches an instance of a function using useCallback(). If its dependencies remain constant, it returns the same function instance in every render. This is especially helpful when callbacks are passed to optimised child components that employ referential equality to avoid re-rendering themselves.

UseRef()

Purpose: The goal of this hook is to produce a mutable reference object with any mutable value stored in its.current property. It retains its value throughout the component’s life. UseRef allows direct access to DOM elements or saving a constant value without re-rendering (unlike useState). It can also prevent memory leaks in asynchronous activities where components unmount before data resolves.

Rules of Hooks

React Hooks contain rules to ensure consistency and avoid bugs:

Only Call Hooks at the Top Level: Only call hooks at the top level, not inside loops, conditions, or nested procedures. React Hooks are called in the same order on each render with this. It creates a functional component’s local state. Avoid using state variables in if conditions to avoid inconsistency. Avoid creating state variables in for loops and functions. Always add them above the functional component.

Only Call Hooks from React Functions: React functional components or custom react hooks are the only of call hooks; standard JavaScript functions and class components are not. You cannot adjust the itemise function. We aim to only run it when necessary. This will demonstrate how to manage API or third-party library performance you cannot control. Start with a parent change without a child change.

Custom Hooks

Stateful logic and side effects can be extracted and reused from functional components by developers with the useful feature known as Custom Hooks. Use in a variety of components. Custom React Hooks can be created as functions that surround fundamental Hooks like useState, useReducer, or useEffect. What they are In JavaScript, a custom Hook is just a function that calls other Hooks and has a name that begins with “use” (e.g., useOnlineStatus, useToken).

Code Reusability: Without generating duplicate code, they allow the sharing of intricate component logic throughout several components. Unlike classes, where you are often linked to the component, react hooks allow you to transfer the stateful logic in and out of the component.

Cleaner Components: Components that are simpler, easier to comprehend, and more focused on displaying user interfaces are achieved by transferring intricate state management or side effect functionality onto a custom Hook.

Separation of Concerns: Custom Hooks facilitate the division of the application’s functionality from its user interface, resulting in a more modular and controllable codebase.

Code Example:

A straightforward functional component that shows a counter and modifies the document title will serve as an example of how to utilise useState and useEffect.

import React, { useState, useEffect } from 'react'; 
function Counter() {
  const [count, setCount] = useState(0); 
  const [message, setMessage] = useState('Hello React!');
  useEffect(() => {
      document.title = `You clicked ${count} times`;
    console.log('Document title updated!');
  }, [count]); 
  useEffect(() => {
    console.log('Component mounted for the first time!');
  }, []); 
  useEffect(() => {
    const timerId = setInterval(() => {
      console.log('Timer ticking...');
    }, 1000);
    return () => {
      clearInterval(timerId); 
      console.log('Timer cleaned up!');
    };
  }, []); 

  return (
    <div>
      <p>{message}</p>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}> {/* Update state using setCount function */}
        Click me
      </button>
      <button onClick={() => setMessage('New message!')}>
        Change Message
      </button>
      <button onClick={() => setCount(0)}>
        Reset Count
      </button>
    </div>
  );
}
export default Counter;

Output:

Hello React!
You clicked 0 times
Click me   Change Message    Reset Count

Explanation of the Code Example

import React, { useState, useEffect } from ‘react’;: We import the required React Hooks, useState and useEffect, from the react library.

function Counter() { … }: This adds functionality to our Counter component. If a React component solely relies on props, it can be a function rather than a class.

const [count, setCount] = useState(0);: Here, the useState Hook is called. 0 is our count state’s starting value. The state variable’s count is its current value. The function we’ll use to update the count state is setCount. When React calls setCount, the Counter component will be immediately re-rendering with the updated count value.

const [message, setMessage] = useState(‘Hello React!’);: As an additional illustration of useState for a distinct piece of state, const [message, setMessage] = useState(‘Hello React!’); shows that a functional component can have multiple independent state variables.

useEffect((): An illustration of useEffect with a dependency array [count] can be found here. The “effect” function in useEffect will run if the count changes after the initial render. It dynamically changes browser page titles.

useEffect(() => { console.log(‘Component mounted for the first time!’); }, []);: This dependent array [] is empty for this useEffect Hook. Thus, the effect method will only run once after component rendering. It helps finish componentDidMount in class components when the component first shows on screen.

return () => { clearInterval(timerId); console.log(‘Timer cleaned up!’); }; }, []);: In addition to having an empty dependency array, this useEffect only executes once on mount. The cleanup method that is returned is crucial (return () => { clearInterval(timerId);… };).

This cleanup procedure executes when the component is DOM-unmounted. Memory leaks are prevented by terminating timers and subscriptions while the component is off. To update the count state, execute the setCount function directly in the event handler: onClick={() => setCount(count + 1)}. React renders the component again in response to this state shift.

Conclusion

React Hooks make React application development modern and efficient by directly extending state and lifecycle functionality to functional components. The official React documentation supports this paradigm shift, which enables stateful logic reuse through custom Hooks, simplifies class binding, and produces shorter, more legible code. React Hooks remain the preferred method for constructing dynamic and interactive React apps, although class components are still helpful for complex use cases or legacy code. This approach also helps developers better understand web standards and JavaScript.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index