Debug School

rakesh kumar
rakesh kumar

Posted on

Explain the concept of react hooks in react js

React Hooks are a feature introduced in React 16.8 that allows functional components to have state and lifecycle features. Previously, these features were only available in class components. Hooks provide a way to write more concise and reusable code by allowing components to manage their state and perform side effects without using class components.

Here's an example to illustrate the concept of React Hooks:

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

In the above code, we have a functional component called Counter that manages a count state using the useState hook. The initial value of count is set to 0 using the useState(0) syntax. The setCount function is used to update the value of count.

We also use the useEffect hook to perform side effects. In this case, we update the document title whenever the count value changes. The useEffect hook takes a callback function as its first argument, which will be executed after the component renders. The second argument is an array of dependencies, which determines when the effect should be re-run. In this case, we specify [count] as the dependency array, so the effect will be re-run whenever the count value changes.

The rendered output displays the current count value and two buttons for incrementing and decrementing the count. When the count value changes, the document title will be updated accordingly.

React Hooks provide a simpler and more intuitive way to manage state and perform side effects in functional components, making the code easier to read and maintain. They eliminate the need for class components and provide a more functional programming style for building React applications.

Another Example

import React, { useState, useEffect } from 'react';

// Custom hook to fetch data from an API
const useFetchData = (url) => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const data = await response.json();

        setData(data);
        setIsLoading(false);
      } catch (error) {
        setError(error);
        setIsLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, isLoading, error };
};

const App = () => {
  const { data, isLoading, error } = useFetchData('https://api.example.com/data');

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Data from API</h1>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In the above code, we define a custom hook called useFetchData that encapsulates the logic for fetching data from an API. The hook takes a url parameter and returns an object containing the fetched data, a isLoading flag to indicate if the data is still being fetched, and an error object in case of any errors.

Inside the useFetchData hook, we use the useState and useEffect hooks to manage the state and perform the data fetching. When the component using this hook mounts or the url dependency changes, the effect is triggered, and the data is fetched from the specified URL.

In the App component, we use the useFetchData custom hook to fetch data from the API endpoint. We destructure the returned values (data, isLoading, error) from the hook and handle different scenarios accordingly. If the data is still loading, we display a loading message. If there is an error, we display an error message. Otherwise, we render the data fetched from the API.

Another Example

import { useState, useEffect } from 'react';

const useFetchData = (url) => {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();

        setData(data);
        setIsLoading(false);
      } catch (error) {
        setError(error);
        setIsLoading(false);
      }
    };

    fetchData();
  }, [url]);

  return { data, isLoading, error };
};

export default useFetchData;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)