Mastering React Hooks: Practical Examples of useState, useEffect, and More

This article explains React Hooks introduced in version 16.8, detailing the purpose and usage of common hooks such as useState, useEffect, useContext, useReducer, useRef, useCallback, and useMemo, and provides practical code examples for each.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Mastering React Hooks: Practical Examples of useState, useEffect, and More

What are Hooks?

Hooks, introduced in React 16.8, allow functional components to use state and other React features without converting to class components. A hook attaches a piece of logic to a data source or event source so that when the source changes, the hooked code re‑executes and produces updated results.

Common Hooks

useState

useState(initialState)

accepts any initial value and returns a two‑element array: the current state value and a setter function. The setter updates state asynchronously; the new value becomes visible on the next render.

function Plus() {
  const [count, setCount] = useState(1);
  function counter() {
    setCount(count + 1);
  }
  return (
    <pre><code><div className='plus'>
      <div>{count}</div>
      <div className='plus-click' onClick={counter}>+</div>
    </div>

); }

useEffect (Side Effects)

useEffect(callback, deps?)

runs code that does not directly produce UI output—e.g., fetching data, updating external variables, or subscribing to events. The callback runs after the render and re‑runs whenever a value in the dependency array changes.

function CountPlus() {
  const [count, setCount] = useState(0);
  const [clickValue, setClickValue] = useState("");

  useEffect(() => {
    setClickValue(`I clicked ${count} times`);
  }, [count]);

  function counter() {
    setCount(count + 1);
  }

  return (
    <pre><code><div className='plus'>
      <div>{count}</div>
      <div className='plus-click' onClick={counter}>+</div>
      <div>{clickValue}</div>
    </div>

); } export default CountPlus;

useContext

useContext(Context)

lets a component consume a value provided by a parent <Context.Provider> without prop‑drilling.

// Create the context
import { createContext } from 'react';
const UserContext = createContext();
export default UserContext;

// Provide a value
import User from "./components/User";
import UserContext from "./components/UserContext";
function App() {
  return (
    <pre><code><div className="App">
      <UserContext.Provider value={{ name: 'Zhang San', sex: 'Male' }}>
        <User />
      </UserContext.Provider>
    </div>

); } export default App; // Consume the context import React, { useContext } from 'react'; import UserContext from './UserContext'; function User() { const user = useContext(UserContext); return (

<div>
      <p>{user.name}</p>
      <p>{user.sex}</p>
    </div>

); } export default User;

useReducer

useReducer(reducer, initialState)

is useful for complex state logic. It returns the current state and a dispatch function that triggers state transitions defined in the reducer.

const reducer = (state, action) => {
  switch (action.type) {
    case 'count':
      return { ...state, count: state.count + 1 };
    default:
      return state;
  }
};

function App() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });
  return (
    <pre><code><div className="App">
      <p>Clicked {state.count} times</p>
      <CountDis dispatch={dispatch} />
    </div>

); } export default App; function CountDis({ dispatch }) { function counter() { dispatch({ type: 'count' }); } return (

<div className='plus'>
      <div className='plus-click' onClick={counter}>+</div>
    </div>

); } export default CountDis;

useRef

useRef(initialValue)

returns a mutable object with a current property. It is commonly used to reference DOM elements or store mutable values that persist across renders.

function CountRef() {
  const inputRef = useRef(null);

  // Focus the input when the component mounts
  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  function showValue() {
    alert(inputRef.current.value);
  }

  return (
    <pre><code><div className='plus'>
      <input ref={inputRef} />
      <div className='plus-click' onClick={showValue}>+</div>
    </div>

); } export default CountRef;

useCallback

useCallback(fn, deps)

memoizes a callback so that the same function instance is returned unless one of the dependencies changes. This prevents unnecessary re‑renders of child components that receive the callback as a prop.

function CountUseCallback() {
  const [count, setCount] = useState(1);
  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, []); // Empty dependency array → stable reference

  return (
    <pre><code><div className='plus'>
      <div>{count}</div>
      <div className='plus-click' onClick={handleClick}>+</div>
    </div>

); } export default CountUseCallback;

useMemo

useMemo(fn, deps)

caches the result of an expensive calculation and recomputes it only when a dependency changes.

function CountMemo({ size }) {
  const result = useMemo(() => {
    // Expensive computation
    if (size < 0) return 0;
    let sum = 0;
    for (let i = 1; i <= size; i++) {
      sum += i;
    }
    return sum;
  }, [size]);

  return (
    <pre><code><div className='plus'>
      <p>{result}</p>
    </div>

); } export default CountMemo;

Conclusion

In typical projects useState, useEffect, useReducer and useRef are used most frequently, while useContext, useMemo and useCallback appear less often. Additional hooks such as useImperativeHandle, useLayoutEffect and custom hooks extend the API for specialized scenarios. Understanding the purpose and proper usage of each hook enables developers to build more maintainable and performant React applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendReacthooksuseReduceruseEffectuseState
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.