React Hooks

Before you jump into react hooks know a little in detail about component and it's types. Checkout my following tutorial on react components.

React Components

If you have worked with older version of react then you will know that you can not use state in a functional components. Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Basically it means you can create a state in a functional component and use it as you would use it with class components. Let's understand it by an example of counter.

import React, { useState } from 'react';

export default = () => {
  // Syntax: const [stateVariable, setFunction] = React.useState(defaultValue);
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

It allows a simple syntax to create a state variable with default value and have a function to set the state variable value. This code is similar to following code.

import React, { Component } from 'react';

class ClickCounter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
    };
  }

  onClickHander = () => {
    const { count } = this.state;
    this.setState({ count: count + 1 });
  };

  render() {
    return (
      <div>
        <p>
          You clicked
          {count}
          times
        </p>
        <button onClick={this.onClickHander}>Click me</button>
      </div>
    );
  }
}

export default ClickCounter;

You can see if you use class component you add lots more logic and consider this duplicate logic for bigger application. It is a smart idea to use hooks and turn this component into functional component.

Advantages of React Hooks

  • It helps you write clean code
  • Eliminates duplicate logic and make your component tiny and small
  • Hooks show real nature of React which is functional
  • Hooks are very convenient to re-use stateful logic