javascript – What are React Hooks?

Question:

I would like to understand the concept and if possible with examples of this new React feature .

  • What will change the way you create projects with React?

  • The community seems to like it, what are the reasons?

Answer:

There are 4 types of Hooks :

Summing up:

" When would I use a Hook? If you write a function component and perform you need to add some state to it, previously you had to convert it to a class. Now you can use a Hook inside the existing function component."

Translating…

" When would I use a hook? If you write a function component and find that you need to add some state to it, previously you had to convert it to a class. Now you can use a hook inside the existing function component."

It was designed for people who are not essentially JS programmers, and have a hard time understanding how this works in the language, so first one had to understand this:

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

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

And now she just needs this:

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

Basically you have a constructor function that returns two values, the first is the created object and the second is a setter that changes the initial value, something like this:

 class Hook { constructor(initialValue) { //Define o valor inicial passado por parâmetro this.value = initialValue //Define a função que altera o valor const setter = newValue => this.value = newValue //Retorna o objeto criado e a função setter return [this, setter]; } //Retorno como string do objeto toString() { return this.value; } } const [value, setter] = new Hook('foo'); console.log(value); setter('bar'); console.log(value); //Aqui vai retornar o valor do toString console.log('Esse é o valor: '+value); //Equivalente a console.log('Esse é o valor: '+value.toString());

What will change the way you create Reacts projects?

You can keep using classes and it won't change anything, but it's now possible to create more complex components in React with simple functions. But it's important to remember that Hooks are only available in version 16.8 or higher.

Scroll to Top