DEV Community

Abdulrahman Ismail
Abdulrahman Ismail

Posted on

React Hooks

React hooks are introduced in React 16.8 React hooks have significantly improved the way developers write React components by promoting reusability, simplifying logic, and enhancing readability. While there might be a learning curve, the benefits often outweigh the drawbacks, making hooks a powerful tool for React development.

There are some benefits of them like, Hooks allow functional components to manage state, side effects, and other React features without the need for class components. This results in cleaner and more concise code. which mean we CAN'T use the hooks in side class components

like

import  { Component } from "react";

class ClassComponentWithHooks extends Component {
  const [count,setCount]=useState();
}

return (
  <div>
    <p>Count: {this.state.count}</p>
    <button onClick={this.handleIncrement}>Increment</button>
  </div>
);

export default ClassComponentWithHooks;
Enter fullscreen mode Exit fullscreen mode

this will give us the error of

  × Unexpected token `[`. Expected * for generator, private key, identifier or async
   ╭─[D:\learning\REACT\practice-hooks\app\page.js:2:1]
 2 │ import  { Component } from "react";
 3 │
 4 │ class ClassComponentWithHooks extends Component {
 5 │   const [count,setCount]=useState();
   ·         ─
 6 │ }
 7 │
 8 │ return (
   ╰────

Caused by:
    Syntax Error
Enter fullscreen mode Exit fullscreen mode

and backing to the class component this is an example of using useState hook

import React, { Component } from 'react';

class ClassComponentWithHooks extends Component {
  constructor(props) {
    super(props);

    // Initialize state using the useState hook equivalent in a class component
    this.state = {
      count: 0,
    };

    // Bind event handler method to the instance
    this.handleIncrement = this.handleIncrement.bind(this);
  }

  // Event handler method
  handleIncrement() {
    // Update state using the setState method
    this.setState((prevState) => ({
      count: prevState.count + 1,
    }));
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.handleIncrement}>Increment</button>
      </div>
    );
  }
}

export default ClassComponentWithHooks;
Enter fullscreen mode Exit fullscreen mode

Reusability:

Custom hooks allow you to extract and reuse stateful logic across different components. This promotes a more modular and reusable code structure.

Example:

import React, { useState } from 'react';

// Custom hook for handling form input
function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  const handleChange = (e) => {
    setValue(e.target.value);
  };

  return {
    value,
    onChange: handleChange,
  };
}

// Example component using the custom hook
function FormComponent() {
  const firstNameInput = useFormInput('');
  const lastNameInput = useFormInput('');

  return (
    <div>
      <label>
        First Name:
        <input type="text" {...firstNameInput} />
      </label>

      <br />

      <label>
        Last Name:
        <input type="text" {...lastNameInput} />
      </label>

      <p>
        Full Name: {firstNameInput.value} {lastNameInput.value}
      </p>
    </div>
  );
}

export default FormComponent;

Enter fullscreen mode Exit fullscreen mode

Explanation:
In this example, the *useFormInput * custom hook encapsulates the logic for handling form input. It initializes a state for the input value using the useState hook and returns an object with the current value and an onChange handler.

The *FormComponent * then uses this custom hook for both the first name and last name inputs. This promotes reusability, as you can easily apply the same form input logic in other components without duplicating code.

Improved Readability:

Hooks encourage a more sequential and linear structure in functional components, making it easier to understand the flow of the component's logic.

And with all of those powerful stuff we have some disadvantages which is NOT actually Disadvantage 😂

we can call them Drawbacks of React Hooks

like Developers familiar with class components may need some time to adjust to the new syntax and paradigm introduced by hooks. and also Hooks are available starting from React version 16.8. If your project uses an older version, you need to upgrade to take advantage of hooks.

finally there are some most important hooks:

1-useState

2-useEffect

3-useContext

4-useReducer

5-useCallback and useMemo

6-useRef

And MUCH more we are going to talk about them one by one in the future

Conclusion

In conclusion, React hooks have brought a transformative shift to how developers approach building components in React. Introduced in version 16.8, these hooks offer a powerful way to manage state, side effects, and other React features within functional components. While there may be a slight learning curve for those accustomed to class components, the benefits of hooks—such as reusability, simplified logic, and enhanced readability—far outweigh any initial challenges.

The ability to create custom hooks further amplifies the modularity of React code, allowing developers to encapsulate and reuse stateful logic across different components. The example of a form input handler demonstrates how custom hooks can promote a more modular and maintainable code structure.

Despite the advantages, it's essential to acknowledge that React hooks are designed for use in functional components, and attempting to use them within class components will lead to errors. Additionally, developers should be mindful of project compatibility, ensuring they are using a version of React that supports hooks.

As we delve into specific hooks like useState, useEffect, useContext, useReducer, useCallback, useMemo, and useRef, the potential for creating efficient and expressive React applications becomes increasingly evident. These hooks empower developers to handle complex state management and side effects with ease.

In the ever-evolving landscape of React development, embracing hooks opens up new possibilities for creating more maintainable, readable, and modular code. As you continue your journey with React, exploring and mastering these hooks will undoubtedly contribute to your effectiveness as a React developer.

Thanks for reading this blog post hope you enjoy it and learn something new and I'm sorry for any mistake or shortcoming.

Top comments (2)

Collapse
 
joseph42a profile image
Joseph42A

Nice explanation, well done!

Collapse
 
abdulrahmanismailhaji profile image
Abdulrahman Ismail

thank you❤️