Code Skiller logoCB Logo
Logo LearnLearnLogo PracticePracticeLogo HireHireLogo IDEIDE

Introduction to Hooks

User image

Published by

sanya sanya

Published at: 28th Jul, 2023
2.85 mins read

Hooks are a feature introduced in React 16.8 that allow functional components to have state, side effects, and lifecycle methods, previously only available in class components. Hooks provide a more concise and flexible way to write components and manage stateful logic.

Hooks are functions that can be used inside functional components to access React features. Some commonly used hooks are mentioned below.

useState

The useState allows us to add the state to the functional components which returns a stateful value along with a function to update that value. You can have multiple useState hooks in a single component, each managing its own state.

The example of the useState is mentioned in the code below -

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

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

useEffect

The useEffect is used to manage side effects in functional components, such as fetching data, subscribing to events, or manipulating the DOM. It accepts a callback function and runs it after every render or when specific dependencies change.

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

const DataFetcher = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://api.example.com/data');
      const result = await response.json();
      setData(result);
    };

    fetchData();
  }, []);

  return <div>{/* Display fetched data here */}</div>;
};

The dependency array (deps array) is an optional argument that allows you to specify which values the effect depends on. The effect will run whenever any of the values in the dependency array change. If the dependency array is empty [], it means the effect will only run once, similar to the behavior of componentDidMount in class components.

The example of how useEffect works with an empty dependency array is mentioned below -

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

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

    // useEffect with empty dependency array
    useEffect(() => {
      console.log('Effect runs!');
  
      // Clean-up function (optional)
      return () => {
        console.log('Clean-up function runs!');
      };
    }, []);
  
    return (
      <div>
        <h1>Count: {count}</h1>
        <button onClick={() => setCount(count + 1)}>Increment</button>
      </div>
    );
  }

useContext

The useContext allows us to access the value of a React context within a functional component which accepts a context object and returns the current value of that context.

import React, { useContext } from 'react';
import MyContext from './MyContext';

const MyComponent = () => {
  const contextValue = useContext(MyContext);

  return <div>{contextValue}</div>;
};

useReducer

The useReduceris an alternative to useState that allows you to manage more complex state transitions. It accepts a reducer function along with an initial state and returns the current state with a dispatch function to trigger state updates.

 import React, { useReducer } from 'react';

 const initialState = { count: 0 };

 const reducer = (state, action) => {
   switch (action.type) {
     case 'increment':
       return { count: state.count + 1 };
     case 'decrement':
       return { count: state.count - 1 };
     default:
       return state;
   }
 };
 
 const Counter = () => {
   const [state, dispatch] = useReducer(reducer,      initialState);
 
   const increment = () => {
     dispatch({ type: 'increment' });
   };
 
   const decrement = () => {
     dispatch({ type: 'decrement' });
   };
 
   return (
     <div>
  <p>Count: {state.count}</p>
  <button onClick={increment}>Increment</button>
  <button onClick={decrement}>Decrement</button>
</div>
   );
 };

Library

WEB DEVELOPMENT

Basic

Frontend

Express JS

React

Hello World in ReactJS

Rendering Elements

States and Lifecycles in React JS

Handling Events in React JS

Introduction to JSX

Components and Props in React JS

Conditional Rendering

Lists and Keys in React JS

Introduction to Redux

Types of components (class vs functional)

Using the useEffect hook

Building custom hooks in React JS

Context API in React JS

Forms in React JS

Lifting State Up in React JS

Composition vs Inheritance

Prop drilling in React JS

Introduction to Hooks

Using the useState hook

UseMemo vs useCallback

Backend

Interview Questions

FAANG QUESTIONS

On this page

useState

useEffect

useContext

useReducer