Nekode
React

Intro to React hooks

An introduction to React hooks

Rifki ahmad fahrezi

Rifki ahmad fahrezi

Introduction

React followed component-based architecture. Component in React is a isolated and reusable bits of code. There is two types of component, which is class component and functional component.

Before React version 16, developers can only using React features like state only in class component, but with version 16.8 React introduced a new featured called hooks. With React hooks we can use common React feature like state not only in class component but also in functional component.

Hooks in React

React hooks is a function that enable functional component to use React state and lifecycle features. React hooks eliminate the need for class component, making the code easier to read, cleaner and maintain.

Basic hooks in React

In this article I will only briefly discuss the basic hooks that are often used in React, for more details, you can check the [official documentation] (https://react.dev/reference/react/hooks).

1. useState

useState is a React hook that allows you to create and manage state in React functional component, here is an example of using the useState hook

import React, { useState } from "react";
 
function Counter() {
    const [count, setCount] = useState(0); 
    return (
        <div>
            <h1>Count: {count}</h1>
            <button onClick={() => 
                setCount(count + 1)}>Increment</button>
        </div>
    );
}

useState return a two variable that can be destructed, which they are the state name on the first index and the state setter on the second index

2. useEffect

useEffect is a React hook that allows you to handle side effects and synchronize a component with external systems. It can be used to manage a component's lifecycle, such as fetching data, managing subscriptions, or performing DOM manipulations.

Here is an example of using react useEffect hook by creating a simple Timer component

import React, { useEffect, useState } from "react";
 
function Timer() {
    const [seconds, setSeconds] = useState(0);
 
    useEffect(() => {
        const interval = setInterval(() => 
            setSeconds((s) => s + 1), 1000);
            
        return () => clearInterval(interval); 
    }, []);
 
    return <h1>Time: {seconds}s</h1>;
}
  • Explanation

    useEffect(() => {
        const interval = setInterval(() => 
            setSeconds((s) => s + 1), 1000);
        return () => clearInterval(interval); // cleanup function
    }, []);

    Purpose: This useEffect sets up a repeating action (a timer) and cleans it up when the component unmounts.

    Inside the useEffect:

    1. setInterval: This function run s a callback every 1000 mililseconds (1 second), the callback updates the seconds state by incrementing it by 1
    2. Cleanup Function: The return statement defines a cleanup function, which React calls when the component unmount or the dependecies change, using clearInterval to Prevents memory leaks by stopping the interval when the component is removed from the DOM.
    3. Empty Dependency Array ([]): This ensure the effect runs only once, similar to componentDidMount in class component

3. useRef

Refs let a component to hold some information that isn’t used for rendering, you can store an information like DOM node using ref. Unlike state updating the ref does not trigger the re-rendering process.

Here is an example of using React useRef hooks, by creating simle input that will automatically focus if the button clicked.

import React, { useRef } from "react";
 
function Focus() {
    const input = useRef();
 
    const focus = () => input.current.focus();
 
    return (
        <div>
            <input ref={input} type="text" />
            <button onClick={focus}>Focus</button>
        </div>
    );
}
  • Explanation

    1. Using useRef to Create a Reference
    const input = useRef(); // initiate the ref
    • The useRef hook creates a reference (input) that can be attached to a DOM element.
    • This reference remains the same across renders and allows you to interact with the DOM element directly via the .current property.
    1. Attaching the Ref to the input element
    <input ref={input} type="text" />
    • The ref attribute links the input reference to the <input>
    1. Focus function
    const focus = () => input.current.focus();
    • What It Does:
      • When called, this function accesses the current property of the input reference, which points to the DOM element (<input/>)
      • The .focus() method is a built-in DOM method that moves the browser’s focus to the input field, making it active and ready for user input

💡

Other than these hooks there is also a lot of React hooks that you can learn more.

Custom hooks

Custom hooks is a hook that we create to encapsulate the reusable logic, Custom hook will enhance the code reusability and readability by sharing the same behavior between a component.

Here is an example of creating a custom hook that used to kwon the screen size:

import { useState, useEffect } from "react";
 
function useScreenSize() {
    const [screenSize, setScreenSize] = useState({
        width: window.innerWidth,
        height: window.innerHeight,
    });
 
    useEffect(() => {
        const handleResize = () => {
            //change the screenSize state value
            setScreenSize({
                width: window.innerWidth,
                height: window.innerHeight,
            });
        };
 
        // Add the resize event listener
        window.addEventListener("resize", handleResize);
 
        // Cleanup the event listener on component unmount
        return () => window.removeEventListener("resize", handleResize);
    }, []);
 
    return screenSize;
}
 
export default useScreenSize;
  • Explanation

    The useScreenSize hook is a custom React hook designed to track the browser's screen dimensions in real-time. It returns the current width and height of the screen and updates these values whenever the window is resized.

  • How to use the useScreenSize hook

    import React from "react";
    import useScreenSize from "./useScreenSize";
     
    function ScreenSizeComponent() {
        // destruct the useScreensize return value
        const { width, height } = useScreenSize();
     
        return (
            <div>
                <h1>Screen Size</h1>
                <p>Width: {width}px</p>
                <p>Height: {height}px</p>
            </div>
        );
    }
     
    export default ScreenSizeComponent;

Benefits of using hooks

Hooks can improve code readability and reusability also make it easier to split complex components into smaller functions.

  • Simpler, cleaner code: Functional components with hooks are often more concise and easier to understand than class components.
  • Better for complex UIs: Hooks make it easier to manage state and side effects in components with intricate logic.
  • Improved maintainability: Code using hooks is often easier to test and debug.

Conclusion

React hooks is one of the basic fundamental you need to know, because it can enhance you code reusability, readability and even performance for you app, I hope you can learn more about the React hooks from the official docs

On this page