DEV Community

Odipo Otieno (KwargDevs)
Odipo Otieno (KwargDevs)

Posted on

React Hooks

React Hooks are functions that allow you to use state and other React features in functional components, which traditionally were only available in class components. They were introduced in React 16.8 and have since become a standard for writing React components. Here's a breakdown of the most commonly used hooks:

1. useState

  • Purpose: Manages state in functional components.
  • Usage:
  import React, { useState } from 'react';

  function Counter() {
    const [count, setCount] = useState(0); // Declare a state variable called 'count'

    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>
          Click me
        </button>
      </div>
    );
  }
Enter fullscreen mode Exit fullscreen mode
  • Explanation: useState returns an array with two elements: the current state value (count) and a function to update it (setCount). This allows you to maintain and update state within a functional component.

2. useEffect

  • Purpose: Handles side effects like fetching data, subscriptions, or manually changing the DOM in functional components.
  • Usage:
  import React, { useEffect, useState } from 'react';

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

    useEffect(() => {
      fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => setData(data));
    }, []); // Empty dependency array means this effect runs once after the initial render.

    return <div>{data ? data : 'Loading...'}</div>;
  }
Enter fullscreen mode Exit fullscreen mode
  • Explanation: useEffect takes two arguments: a function to run the effect and an optional dependency array. The effect function runs after the component renders. If you provide a dependency array, the effect will only run when those dependencies change.

3. useContext

  • Purpose: Accesses the value of a context within a functional component.
  • Usage:
  import React, { useContext } from 'react';
  const ThemeContext = React.createContext('light');

  function DisplayTheme() {
    const theme = useContext(ThemeContext); // Access the current theme context value

    return <div>The current theme is {theme}</div>;
  }
Enter fullscreen mode Exit fullscreen mode
  • Explanation: useContext allows you to consume context values directly in functional components without needing a Consumer component.

4. useReducer

  • Purpose: Manages complex state logic in functional components, acting as an alternative to useState.
  • Usage:
  import React, { useReducer } from 'react';

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

  function Counter() {
    const [state, dispatch] = useReducer(reducer, { count: 0 });

    return (
      <div>
        <p>Count: {state.count}</p>
        <button onClick={() => dispatch({ type: 'increment' })}>+</button>
        <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      </div>
    );
  }
Enter fullscreen mode Exit fullscreen mode
  • Explanation: useReducer is useful for managing state that depends on more complex logic or multiple actions. It takes a reducer function and an initial state and returns the current state and a dispatch function.

5. useRef

  • Purpose: Accesses and stores a mutable reference to a DOM element or value that persists across renders.
  • Usage:
  import React, { useRef, useEffect } from 'react';

  function TextInputWithFocusButton() {
    const inputEl = useRef(null);

    const onButtonClick = () => {
      inputEl.current.focus(); // Access the DOM element directly
    };

    return (
      <>
        <input ref={inputEl} type="text" />
        <button onClick={onButtonClick}>Focus the input</button>
      </>
    );
  }
Enter fullscreen mode Exit fullscreen mode
  • Explanation: useRef returns a mutable object with a .current property that can hold a value or a reference to a DOM element. This value persists across renders without triggering re-renders when updated.

6. useMemo and useCallback

  • Purpose: Optimize performance by memoizing expensive calculations or functions.
  • Usage:
  import React, { useMemo, useCallback } from 'react';

  function Example({ items }) {
    const expensiveCalculation = useMemo(() => {
      return items.reduce((a, b) => a + b, 0);
    }, [items]);

    const memoizedCallback = useCallback(() => {
      console.log('This function is memoized');
    }, []);

    return <div>{expensiveCalculation}</div>;
  }
Enter fullscreen mode Exit fullscreen mode
  • Explanation: useMemo memoizes a computed value, recomputing it only when its dependencies change. useCallback memoizes a function, ensuring it's only redefined when its dependencies change.

Why Hooks Are Useful

  • Cleaner Code: Hooks allow you to write cleaner, more readable code without the need for class components.
  • Reusability: Hooks can be reused across different components or even shared between projects.
  • Stateful Logic in Functional Components: Hooks enable you to manage state and side effects in functional components, making them as powerful as class components.

Hooks have transformed the way developers write React applications, making functional components more capable and easier to manage.

Top comments (0)