What is a Hook in React? 🪝

Hooks are functions that let you use state and other React features without writing a class. Introduced in React 16.8, hooks provide a way to manage state and side effects in functional components, making your code more concise and easier to understand.

Built-in Hooks in React 🔧

There are several built-in hooks in React, such as:

How are Custom Hooks Made? 🛠️

Custom hooks allow you to encapsulate reusable logic and share it across multiple components. A custom hook is simply a JavaScript function whose name starts with "use" and that may call other hooks.

Creating a Custom Hook

  1. Define the Custom Hook Function:
  2. Use the Custom Hook in Your Components:

Example: Creating and Using a Custom Hook

Let's create a simple custom hook called useLocalStorage that helps manage state with localStorage.

// useLocalStorage.js
import { useState } from 'react';

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.log(error);
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

export default useLocalStorage;

Using the Custom Hook

Now, let's use this custom hook in a component:

// App.js
import React from 'react';
import useLocalStorage from './useLocalStorage';

function App() {
  const [name, setName] = useLocalStorage('name', 'Bob');

  return (
    <div>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <p>Hello, {name}!</p>
    </div>
  );
}

export default App;