profile

Hooks in ReactJS

Hooks is a feature introduced in React 16.8 that allow you to use state and other React features in functional components. Before the introduction of hooks, functional components were stateless and couldn't hold their own state or use lifecycle methods. With hooks, functional components can now have state, side effects, and more, making them just as powerful as class components. Here's an overview of hooks in React.js:

1. State Hook: useState

  import React, { useState } from 'react';

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

    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={() => setCount(count + 1)}>Increment</button>
      </div>
    );
  }

2. Effect Hook: useEffect

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

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

    useEffect(() => {
      document.title = `You clicked ${count} times`;
    }, [count]);

    return (
      <div>
        <p>You clicked {count} times</p>
        <button onClick={() => setCount(count + 1)}>Click me</button>
      </div>
    );
  }

3. Context Hook: useContext

  import React, { useContext } from 'react';
  import MyContext from './MyContext';

  function MyComponent() {
    const value = useContext(MyContext);
    return <div>{value}</div>;
  }

4. Reducer Hook: useReducer

  import React, { useReducer } from 'react';

  function reducer(state, action) {
    switch (action.type) {
      case 'increment':
        return { count: state.count + 1 };
      case 'decrement':
        return { count: state.count - 1 };
      default:
        throw new Error();
    }
  }

  function Counter() {
    const [state, dispatch] = useReducer(reducer, { count: 0 });

    return (
      <div>
        Count: {state.count}
        <button onClick={() => dispatch({ type: 'increment' })}>+</button>
        <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      </div>
    );
  }

5. Custom Hooks:

  import { useState, useEffect } from 'react';

  function useFetch(url) {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
      const fetchData = async () => {
        try {
          const response = await fetch(url);
          const result = await response.json();
          setData(result);
        } catch (error) {
          setError(error);
        } finally {
          setLoading(false);
        }
      };

      fetchData();
    }, [url]);

    return { data, loading, error };
  }

  export default useFetch;

Benefits of Hooks:

Considerations:

Hooks have become an essential part of React development, offering a more functional and expressive way to build components. They provide a simpler, more flexible, and efficient alternative to class components. With hooks, you can build powerful and maintainable React applications with ease.