React Hooks
ref:https://dev.to/pratham10/all-you-need-to-know-about-react-hooks-54p0

React Hooks

What are React Hooks ?

Hooks let us use different React features from your components. We can either use the built-in Hooks or combine them to build your own.

Rules of Hooks

  • We can use React Hooks inside function components only.
  • Only call hooks at top level. We cannot call hooks inside loops, conditions, or nested functions, they should always be called at the top of function component.
  • We cannot call hooks from regular JavaScript functions.

Benefits of using React hooks

  1. Simplified Logic: Reduce boilerplate and simplify state management.
  2. Reusability: Encourage code reuse across components.
  3. No Class Syntax: Eliminate class components for easier learning and cleaner code.
  4. Enhanced Lifecycle Management: Hooks streamline lifecycle management with useEffect, making it easier to handle side effects.
  5. Performance Optimization: Hooks like useMemo and useCallback aid performance by memoizing values and callbacks, preventing unnecessary re-renders.

Built-in and Custom hooks

React have few built-in hooks and can also create our own custom hooks in React.

Built-in hooks:

useState: useState is a React Hook that lets us add a state variable to our component.

const [state, setState] = useState(initialState)        

initialState: The value we want the state to be initially.

useState returns an array with exactly two values:

  1. The current state. During the first render, it will match the initialState you have passed.
  2. The set function that lets you update the state to a different value and trigger a re-render.

useEffect: useEffect is a React Hook that lets you synchronize a component with an external system.

useEffect(setup, dependencies?)         

setup: The function with our Effect’s logic. Our setup function may also optionally return a cleanup function. When our component is added to the DOM, React will run our setup function. After every re-render with changed dependencies, React will first run the cleanup function (if we provided it) with the old values, and then run our setup function with the new values.

optional dependencies: The list of all reactive values referenced inside of the setup code.

useEffect returns undefined

To understand the useEffect hook you first need to understand lifecycle of the component. The lifecycle of the component contains three main parts i.e. mounting, updating and unmounting.

mounting: when the page loads

updating: when the state updates

unmounting: when user leaves the page

but when using React hooks, we can just do everything through the useEffect hook.

useMemo: useMemo is a React Hook utilized for memoizing expensive calculations. It aims to optimize performance by caching the result of a computation and only recomputing it when the dependencies change.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);        

useMemo memoizes the result of the function passed as the first argument. It re-executes the function only if any of the dependencies provided in the array ([a, b]) change.

useRef: useRef is a Hook used to create a mutable reference that persists across renders. It's commonly employed to access the DOM or to store mutable values that don't trigger re-renders.

const myRef = useRef(initialValue);        

The myRef object persists for the entire lifecycle of the component. It doesn't cause re-renders when its value changes.


useReducer: useReducer is a Hook that offers an alternative to useState for managing complex state logic. It's particularly useful when the state transitions depend on the previous state.

const [state, dispatch] = useReducer(reducer, initialState);        

useReducer follows the reducer pattern familiar from Redux. It takes a reducer function and an initial state as arguments, returning the current state and a dispatch function to trigger state transitions.

Custom hooks:

Custom hook is a JavaScript function that encapsulates a specific piece of logic. It allows us to reuse stateful logic across different components, making our codebase cleaner, more organized, and highly maintainable.

The magic happens when we prefix our custom function with “use” — that’s React’s signal that you’re dealing with a custom hook.

Custom hooks can encapsulate any stateful logic, such as fetching data, managing timers, or handling subscriptions. Once defined, they can be reused across multiple components, promoting code modularization and reducing duplication.

Creating our Custom Hook

import { useState } from 'react';
const useCounter = () => {
  const [count, setCount] = useState(0);

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

  const decrement = () => {
    setCount(count - 1);
  }

  return { count, increment, decrement };
}

export default useCounter;        

Using a Custom Hook

import React from 'react';
import useCounter from './useCounter';

const Counter = () => {
  const { count, increment, decrement } = useCounter();

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

export default Counter;        

Use Cases

  1. Data Fetching: Create a custom hook for fetching data from APIs, handling loading and error states, and caching responses.
  2. Form Handling: Abstract away the form state management, input validation, and submission logic into a reusable form handling custom hook.
  3. Authentication: Develop a custom hook for managing user authentication, including login, registration, and session management.
  4. Local Storage: Simplify local storage interactions by encapsulating read and write operations in a custom hook.


To view or add a comment, sign in

Others also viewed

Explore content categories