Introduction to React Hooks
Tags: react
Published: 2020-10-20 13:55:00

This blog will be a brief introduction to React Hooks. Examples will include useState and useEffect Hooks. More hooks can be found with React's _Hooks API Reference_ [here](https://reactjs.org/docs/hooks-reference.html).

## Functional vs Class Components

Typically when using state in Reactjs, you’ll need to create a class component and store the code in a state object. Using Hooks, you are able to create state in a regular Javascript functional component. Another benefit is that functions initialized in the hook will retain their scope without binding it inside of the class constructor. These features are beneficial because it allows for cleaner and less chucky code. 

Below is a comparison between a React feature created with a functional component and a class component. 

_Functional Component with Hooks_

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

export default function Example() {
  //declare a state
  const [action, setAction] = useState(['blog']);

  const handleClick = () => {
    if(action === 'blog'){
      setAction('run');
    } else if (action === 'run'){
      setAction('blog');
    }
  }
  return (
    <div>
      <p>Todo: {action}</p>
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );
}
```

_Class Component_

```
import React, { Component } from 'react';

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      action: 'blog',
    }
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    if(action === 'blog'){
      this.setState({action: 'run'});
    } else if (action === 'run'){
      this.setState({ action: 'blog' });
    }
  }
  render() {
    const action = this.state.action;
    return (
      <div>
        <p>Todo: {action}</p>
        <button onClick={this.handleClick}>
          Click me
        </button>
      </div>
    );
  }
}
```

## LifeCycle

To run code during major React lifecycle events, such as ComponentDidMount, you can call the Hook useEffect. React explains, "Unlike componentDidMount and componentDidUpdate, the function passed to useEffect fires after layout and paint, during a deferred event." If necessary, adding the array literal as a argument in useEffect specifies that useEffect should only be called when he Example Component loads. This can prevent as side effect where useEffect is infinitely being called.

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

export default function Example() {
  //declare a state
  const [action, setAction] = useState([]);

  //API Request
  const someAsyncFunction = async () => {
    try {
      const result = await someApiResult();
      setAction(result);
    } catch (error) {
      //do somethings with the error
    }
  }

  useEffect(()=>{
    someAsyncFunction();
  }, []); // can be called with or without the array literal

  return (
    <div>
      <ul>
        ToDo:
        <li>{action}</li>
      </ul>
    </div>
  );
}
```

## Rules of React Hooks
The React [documentation](https://reactjs.org/docs/hooks-rules.html) outlines a few rules to ensure best practice for your application.
* Use functional components
* It is okay to use multiple State and Effect Hooks in a single component, just outline your Hooks in the order in which they should be called.
* This is why Hooks must be called on the top level of our components.
* Hooks should not be used inside of loops, conditions, or nested functions

## Conclusion
I hope you enjoyed this brief introduction. You could always read more on React Hooks documentation.