DEV Community

Cover image for React Hooks: A Beginner's Guide
Philip Walsh
Philip Walsh

Posted on

React Hooks: A Beginner's Guide

In this article, we'll explore React HooksuseState, useEffect, useMemo, and useRef. These hooks allow you to manage state, handle side effects, optimize performance, and interact with the DOM in functional components. Let's dive in and understand how to use them effectively in your React projects.

Table of Contents

  1. useState - Managing Component State
  2. useEffect - Handling Side Effects
  3. useMemo - Optimizing Performance
  4. useRef - Accessing DOM Elements
  5. Conclusion

1. useState - Managing Component State

useState lets you add state to functional components. It's perfect for storing and updating data that changes during the component's lifecycle, like form inputs, counters, or toggles.

Syntax:

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • state: Current value of the state.
  • setState: Function to update the state.
  • initialValue: Initial value for the state.

Example:

import React, { useState } from 'react';

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

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Live Demo on CodePen


2. useEffect - Handling Side Effects

useEffect is used for side effects such as fetching data, subscribing to services, or setting up event listeners. By default, it runs after every render, but you can control when it runs with dependency arrays.

Syntax:

useEffect(() => {
  // Side effect logic
  return () => {
    // Cleanup logic
  };
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode
  • cleanup function: Runs when the component unmounts or before the effect re-runs.
  • dependencies array: Tells React when to re-run the effect.

Example:

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

const Timer = () => {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => setSeconds(prev => prev + 1), 1000);
    return () => clearInterval(interval);
  }, []);

  return <h1>{seconds} seconds</h1>;
};
Enter fullscreen mode Exit fullscreen mode

Live Demo on CodePen


3. useMemo - Optimizing Performance

useMemo memoizes expensive calculations, preventing unnecessary recalculations on every render. It's ideal for performance optimization when dealing with heavy computations.

Syntax:

const memoizedValue = useMemo(() => expensiveCalculation(), [dependencies]);
Enter fullscreen mode Exit fullscreen mode
  • memoizedValue: The result of the memoized computation.
  • dependencies: Values that trigger recalculation.

Example:

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

const Fibonacci = ({ n }) => {
  const calculateFibonacci = (n) => {
    if (n <= 1) return n;
    return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
  };

  const fibonacci = useMemo(() => calculateFibonacci(n), [n]);

  return <h1>Fibonacci of {n} is {fibonacci}</h1>;
};
Enter fullscreen mode Exit fullscreen mode

Live Demo on CodePen


4. useRef - Accessing DOM Elements

useRef is used to reference DOM elements or store mutable values that don’t trigger re-renders. It’s commonly used for focusing inputs or measuring element dimensions.

Syntax:

const ref = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • ref: A mutable object storing the current reference.

Example:

import React, { useRef } from 'react';

const FocusInput = () => {
  const inputRef = useRef(null);

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={() => inputRef.current.focus()}>Focus Input</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Live Demo on CodePen


Conclusion

React hooks like useState, useEffect, useMemo, and useRef empower you to manage component state, handle side effects, optimize performance, and interact with the DOM in a more intuitive way. Mastering these hooks will help you write cleaner, more efficient React code.

By incorporating these hooks into your workflow, you'll be able to build more powerful and maintainable React applications. Happy coding!

Top comments (0)