Shravani Thirunagari
Shravani Roy

Follow

Shravani Roy

Follow

5 commonly used react hooks

Shravani Thirunagari's photo
Shravani Thirunagari
·Mar 21, 2023·

3 min read

I have 5 plus years of experience in using React js in real-time applications. I started with component life cycle methods in class components and gradually moved to functional components. I have found functional components easy to use and manage. Once, I got a task to migrate some old project's codebase into functional components, which build muscle memory around the react hooks. In this post, I have shared the 5 most commonly used react hooks with some simple examples.

  1. useState :

    The useState hook is used for managing the state within a functional component. Here's an example of how to use it to display a simple form:

import { useState } from 'react';

function Form() {
  const [formData, setFormData] = useState({ name: '', email: '', message: '' });

  const handleInputChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevFormData) => ({ ...prevFormData, [name]: value }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" name="name" value={formData.name} onChange={handleInputChange} />
      <input type="email" name="email" value={formData.email} onChange={handleInputChange} />
      <textarea name="message" value={formData.message} onChange={handleInputChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

In this example, useState is used to manage the state of a form. The formData object contains the current values of the form inputs and is updated via the handleInputChange function. The handleSubmit function logs the form data to the console when the form is submitted.

  1. useEffect :

    The useEffect hook is used for performing side effects within a component, such as fetching data from an API. Here's an example of how to use it to fetch data from a fake API:

import { useState, useEffect } from 'react';

function Data() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(json => setData(json))
  }, []);

  return (
    <ul>
      {data.map(item => (
        <li key={item.id}>{item.title}</li>
      ))}
    </ul>
  );
}
  1. useContext :

    The useContext hook is used for accessing context within a component. Here's an example of how to use it to change the theme of an app:

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function Theme() {
  const theme = useContext(ThemeContext);

  return (
    <div className={`theme-${theme}`}>
      <p>Current theme: {theme}</p>
    </div>
  );
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Theme />
    </ThemeContext.Provider>
  );
}
  1. useRef :

    The useRef hook is used for creating a reference to a component or element within a component. Here's an example of how to use it to focus on an input element:

import { useRef } from 'react';

function Input() {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  }

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={handleClick}>Focus</button>
    </div>
  );
}
  1. useCallback :

    The useCallback hook is used for memoizing a function within a component. Here's an example of how to use it to memorize a handler function:

import { useCallback, useState } from 'react';

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}

In this example, useCallback is used to memoize the handleIncrement function. Since handleIncrement does not depend on any variables outside of its scope, it is only created once when the component is mounted, rather than being recreated on every render. This can help improve performance, particularly for expensive calculations or when passing functions down as props to child components.

I hope this was helpful. Thank you! Happy learning.

 
Share this