Understanding React Hooks

July 15, 2024

Understanding React Hooks

React Hooks have revolutionized the way we write components. Before hooks, we had to rely on class components to manage state or lifecycle methods. Now, with hooks like useState, useEffect, and useContext, we can use state and other React features in functional components.

useState

The useState hook is the most common one. It lets you add state to functional components.

import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

This is just the tip of the iceberg. Hooks allow for cleaner, more reusable code.