REACT Tutorial



HOOKS IN REACT


Hooks in React

Hooks are special functions introduced in React 16.8 that let you "hook into" React state and lifecycle features from function components. They enable function components to have state and other React features without writing a class.

Why Hooks?
Before hooks, only class components could manage state and lifecycle. Hooks allow cleaner, simpler, and reusable code with functional components.

Commonly Used Hooks

  • useState: Manage local component state.
  • useEffect: Perform side effects like data fetching or subscriptions.
  • useContext: Access React context easily.
  • useRef: Reference DOM elements or keep mutable values.

Example: Using useState Hook

import React, { useState } from 'react';

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

  return (
    <div style={{ textAlign: 'center', marginTop: '30px' }}>
      <h2>Count: {count}</h2>
      <button
        onClick={() => setCount(count + 1)}
        style={{
          padding: '12px 24px',
          fontSize: '16px',
          cursor: 'pointer',
          backgroundColor: '#2196f3',
          color: '#fff',
          border: 'none',
          borderRadius: '8px',
          marginTop: '12px'
        }}
      >Increase</button>
    </div>
  );
}
  

In this example, useState creates a state variable count with initial value 0 and a function setCount to update it. Clicking the button increases the count dynamically.

Hooks let you write clean and reusable logic without needing classes. Explore and experiment with different hooks to build powerful React apps!

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review