How to Use Hooks in React?

React Hooks are one of the most exciting features introduced in React 16.8, allowing you to use state and other React features without writing a class. They make your code more readable, reusable, and maintainable. If you're just starting with React or transitioning from class-based components to functional components, this guide will help you understand the basics of React Hooks.

What Are Hooks?

Hooks are functions that let you "hook into" React's state and lifecycle features from function components. They enable you to manage state, side effects, context, refs, and more within functional components, which were previously only possible with class components.

Basic Hooks in React

There are several built-in hooks in React, but as a beginner, you'll primarily work with three.

  1. useState: Manages state in a functional component.
  2. useEffect: Handles side effects like data fetching or subscriptions.
  3. useContext: Accesses and manages context, which is a way to pass data through the component tree without manually passing props down at every level.

useState Hook

The `useState` hook is used to add a state to a functional component.

Example

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>
  );
}

In this example

  1. `useState(0)` initializes the state variable `count` to `0`.
  2. `setCount` is the function used to update the state.
  3. The button click increases the count by 1 each time it's pressed.

useEffect Hook

The `useEffect` hook lets you perform side effects in function components. It’s similar to `componentDidMount`, `componentDidUpdate`, and `componentWillUnmount` in class components.

Example

import React, { useState, useEffect } from 'react';
function Example() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

In this example

  1. `useEffect` runs after every render, updating the document title with the current `count`.
  2. You can also control when `useEffect` runs by providing a dependency array as the second argument. For example, `useEffect(() => { ... }, [count]);` only re-runs when `count` changes.

useContext Hook

The `useContext` hook is used to access the value of a context directly in a functional component. This is useful when you want to avoid prop drilling (passing props down multiple levels).

Example

import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>I am styled by theme context!</button>;
}
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}

In this example

  1. `useContext(ThemeContext)` accesses the current value of `ThemeContext`.
  2. The button’s class is set based on the context value provided by `ThemeContext.Provider`.

Rules of Hooks

There are two main rules you need to follow when using Hooks.

  1. Call Hooks at the top level: Don’t call Hooks inside loops, conditions, or nested functions. Always use them at the top level of your React function so that React knows the order of Hooks calls.
  2. Call Hooks only from React functions: Don’t call Hooks from regular JavaScript functions. They should only be called from React functional components or custom Hooks.

Conclusion

React Hooks are powerful tools that simplify the way you manage state and lifecycle methods in your functional components. By mastering `useState`, `useEffect`, and `useContext`, you'll be well on your way to writing clean, maintainable React code. As you become more comfortable with these basic hooks, you can explore other hooks like `useReducer`, and `useRef`, and even create your own custom hooks to encapsulate reusable logic.

Happy coding!