React Hooks

React Hooks

React Hooks revolutionized how functional components work by allowing them to manage state and side effects. Let’s dive into some essential React Hooks:

What is a Hook?

A Hook is a special function provided by React that allows you to use state and other React features without writing a class. Hooks are functions that let you “hook into” React state and lifecycle features from functional components.

React useState Hook

The useState Hook is the most commonly used Hook. It allows functional components to manage state. useState returns a stateful value and a function to update it.

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

React useEffect Hook

The useEffect Hook allows functional components to perform side effects, such as data fetching, subscriptions, or manually changing the DOM, after rendering. It combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount in class components.

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

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

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

React useContext Hook

The useContext Hook provides a way to consume context in functional components. It allows you to access the nearest current value of a context.

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

function MyComponent() {
  const value = useContext(MyContext);
  return <div>{value}</div>;
}

React useRef Hook

The useRef Hook returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

import React, { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);
  const focusInput = () => {
    inputEl.current.focus();
  };

  return (
    <div>
      <input ref={inputEl} type="text" />
      <button onClick={focusInput}>Focus the input</button>
    </div>
  );
}

React useReducer Hook

The useReducer Hook is an alternative to useState that is usually preferable when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.

import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

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

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  );
}

React useCallback Hook

The useCallback Hook returns a memoized callback. It is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

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

function Button({ onClick, children }) {
  return <button onClick={onClick}>{children}</button>;
}

function App() {
  const [count, setCount] = useState(0);
  const increment = useCallback(() => setCount(count + 1), [count]);

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

React useMemo Hook

The useMemo Hook memoizes the result of a function. It is useful for optimizing performance by memoizing expensive calculations so that they are only computed when the inputs change.

import React, { useMemo } from 'react';

function ExpensiveComponent({ data }) {
  const result = useMemo(() => {
    // Expensive calculation based on data
    return data.reduce((acc, curr) => acc + curr, 0);
  }, [data]);

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

These React Hooks provide powerful capabilities to functional components, making them more versatile and expressive. By mastering these hooks, you can write cleaner and more efficient React code.

shreyasingh
shreyasingh
Articles: 9