Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to React

React Hooks: useState and useEffect Explained

React2,800 viewsBy Muhammad Fareed
reacthooksusestateuseeffect

React Hooks: useState and useEffect

Master React Hooks with detailed explanations of useState and useEffect, the most commonly used hooks.

useState Hook

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

import { useState } from 'react';

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

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

useEffect Hook

The useEffect hook handles side effects in functional components.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch('/api/data')
      .then(res => res.json())
      .then(data => setData(data));
  }, []); // Empty array = run once

  return <div>{data ? data.name : 'Loading...'}</div>;
}

Common Patterns

Dependency Array

useEffect(() => {
  // Runs when 'count' changes
}, [count]);

Cleanup Function

useEffect(() => {
  const timer = setInterval(() => {
    console.log('Tick');
  }, 1000);

  return () => clearInterval(timer);
}, []);