DEV Community

Cover image for 🧠 Understanding useState, useEffect, and useRef in React (with Simple Examples)
Satya Samaikya Venna
Satya Samaikya Venna

Posted on

🧠 Understanding useState, useEffect, and useRef in React (with Simple Examples)

React is a powerful JavaScript library for building user interfaces. If you're new to React or hooks, you might be wondering what these things are:

  • useState

  • useEffect

  • useRef

These are React Hooks β€” functions that let you use state and other React features without writing a class.

In this blog, let's explore each one with simple examples and easy explanations.


πŸ”„ useState - Managing State in Functional Components

The useState hook allows you to add state to your functional components.

βœ… Syntax

const [state, setState] = useState(initialValue);

Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Example: Counter App

import React, { useState } from 'react';

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

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default Counter;

Enter fullscreen mode Exit fullscreen mode

πŸ“˜ Explanation

  • count is the state variable.

  • setCount is the function to update count.

  • useState(0) initializes the count with 0.


βš™οΈ useEffect – Side Effects in Components

The useEffect hook lets you perform side effects like:

  • Fetching data

  • Updating the DOM

  • Subscribing to events

βœ… Syntax

useEffect(() => {
  // Your code here
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Example: Log Count Changes

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

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

  useEffect(() => {
    console.log(`Count has changed to: ${count}`);
  }, [count]);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default CounterWithEffect;

Enter fullscreen mode Exit fullscreen mode

πŸ“˜ Explanation

  • The useEffect runs after the component renders.

  • It only runs again when count changes because of the [count] dependency.


🧷 useRef – Referencing DOM Elements or Storing Values

The useRef hook gives you a way to:

  • Access DOM elements directly

  • Store mutable values that don’t cause re-renders

    βœ… Syntax

const myRef = useRef(initialValue);
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Example: Focus an Input

import React, { useRef } from 'react';

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

  const handleFocus = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" placeholder="Type here..." />
      <button onClick={handleFocus}>Focus Input</button>
    </div>
  );
}

export default FocusInput;
Enter fullscreen mode Exit fullscreen mode

πŸ“˜ Explanation

  • inputRef is linked to the input using ref={inputRef}.

  • inputRef.current gives you access to the actual DOM element.

  • Clicking the button focuses the input.


βœ… Summary Table

Hook Purpose Triggers Re-render? Example Usecases
useState Add local state to a component βœ… Yes Counter, Form inputs
useEffect Run side-effects (after render) βœ… Depends on deps API calls, timers
useRef Access DOM or store mutable values ❌ No Focus input, timer IDs

πŸš€ Final Thoughts

React Hooks make it easier to write clean, functional components without the complexity of classes. Here's a quick rule of thumb:

  • Use useState to store values that change and affect UI.

  • Use useEffect to handle side effects like fetching data or setting up subscriptions.

  • Use useRef when you want to persist values or directly interact with the DOM.


Happy Coding! πŸŽ‰

Let me know if you want examples for advanced hooks or how to combine them!
Satya Samaikya Venna

Top comments (0)