DEV Community

Brianna Skinner
Brianna Skinner

Posted on

Introduction to React Hooks

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.

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

Rules of React Hooks

The React documentation 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.

Top comments (0)