What is Hooks?

Understanding React Hooks fundamentals

🪝 What are React Hooks?

React Hooks are special functions that let you use state and other React features in functional components. They were introduced in React 16.8 to simplify component logic without writing classes.


import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  
  return <button>Count: {count}</button>;
}
                                    

Common React Hooks

📊

useState

Manage component state

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

useEffect

Handle side effects

useEffect(() => {
  // Side effect code
}, []);
🌐

useContext

Share data globally

const value = useContext(MyContext);
🎯

useRef

Reference DOM elements

const ref = useRef(null);

🔹 Why Use Hooks?

Hooks solve many problems that existed with class components. They make your code cleaner, easier to understand, and more reusable without the complexity of classes.

Benefits of Hooks:

  • Simpler code: No need for class syntax or 'this' keyword
  • Reusable logic: Create custom hooks to share logic
  • Better organization: Group related code together
  • Easier testing: Functions are simpler to test than classes
  • Smaller bundle: Less code means faster loading

🔹 Before Hooks (Class Component)

Before hooks, you needed to write class components to use state and lifecycle methods. This required more boilerplate code and understanding of 'this' binding.

// Old way with class component
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }
  
  increment = () => {
    this.setState({ count: this.state.count + 1 });
  }
  
  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>
          Increment
        </button>
      </div>
    );
  }
}

🔹 After Hooks (Functional Component)

With hooks, the same functionality is much simpler and cleaner. You can use state and other features in functional components without classes.

// New way with hooks
import { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);
  
  const increment = () => {
    setCount(count + 1);
  };
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>
        Increment
      </button>
    </div>
  );
}

Output:

Count: 0

🔹 Rules of Hooks

React Hooks have two important rules you must follow to ensure they work correctly. These rules help React keep track of hook state between renders.

Rule #1: Only Call Hooks at the Top Level

Don't call hooks inside loops, conditions, or nested functions. Always use hooks at the top level of your React function.

// ❌ Wrong - Hook inside condition
function Component() {
  if (condition) {
    const [state, setState] = useState(0); // Bad!
  }
}

// ✅ Correct - Hook at top level
function Component() {
  const [state, setState] = useState(0); // Good!
  
  if (condition) {
    // Use state here
  }
}

Rule #2: Only Call Hooks from React Functions

Call hooks only from React functional components or custom hooks, not from regular JavaScript functions.

// ❌ Wrong - Hook in regular function
function regularFunction() {
  const [state, setState] = useState(0); // Bad!
}

// ✅ Correct - Hook in React component
function MyComponent() {
  const [state, setState] = useState(0); // Good!
}

// ✅ Correct - Hook in custom hook
function useCustomHook() {
  const [state, setState] = useState(0); // Good!
}

🔹 Creating Custom Hooks

You can create your own hooks to reuse stateful logic across components. Custom hooks are functions that start with "use" and can call other hooks.

// Custom hook for form input
function useInput(initialValue) {
  const [value, setValue] = useState(initialValue);
  
  const handleChange = (e) => {
    setValue(e.target.value);
  };
  
  return [value, handleChange];
}

// Using the custom hook
function LoginForm() {
  const [username, setUsername] = useInput('');
  const [password, setPassword] = useInput('');
  
  return (
    <form>
      <input 
        value={username} 
        onChange={setUsername} 
        placeholder="Username" 
      />
      <input 
        value={password} 
        onChange={setPassword} 
        type="password"
        placeholder="Password" 
      />
    </form>
  );
}

Output:

🧠 Test Your Knowledge

When were React Hooks introduced?