What are React Hooks?

Asked

Viewed 2,779 times

20

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

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

  • The community seems to have enjoyed, what are the reasons?

3 answers

10


There are 4 types of hooks:

In short:

"When would I use a Hook? If you write a Function Component and realize 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 I’d use a hook? If you write a function component and realize that you need to add some state to it, you previously 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 difficulty understanding how the this works in language, so before the person had to understand it:

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 all she needs is 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, more or less 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 in the way that Reacts projects are created?

You can continue using classes and will not change anything, but you can now 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.

6

What are Hooks?

Hooks are a set of new features that allow the developer to control the state in a simpler, faster and more intuitive way.

Its implementation started with version 16.7.0-alpha.0 and the promise is that the developer will be able to move gradually from the standard currently used to the Hooks without Breaking Changes and without breaking the head too much, being able at first to use both forms.

Hooks are classified into basic and additional as follows:

Basic hooks:

  • useState
  • useEffect
  • useContext

Additional hooks:

  • useReduce
  • useCallback
  • useMemo
  • useRef
  • useImperativeMethods
  • useMutationEffect
  • useLayoutEffect

Explaining the Basic Hooks.

The useState allows you to read and store the information in an easier and practical way in the state, eliminating some class components and replacing them with functional components.

The useEffect is the hook we use to perform functions that need or perform some effect on the component, for example mutations, subscriptions, timers and logging. Has the same effect as componentDidMount and componentDidUpdate has in the classes.

The useContext is a hook that allows you to use Context passing the state between the Provider (where the state comes from) and Consumer (who will receive) components more easily and quickly.

Completion.

The Hooks came to help the developer write components in a simpler, readable way.

There will be no need to refactor all the class and the whole project. They will not break your code and you can even write both ways until you get used to them.

The Hooks will also not kill the Redux, even can be used with it.

Care must be taken when using Hooks such as useMutationEffect and useLayoutEffect, as they can cause unwanted effects and performance issues.

On my blog there is an example with a link to download the code on github

https://bognarjunior.wordpress.com/2018/11/04/react-hooks-entendendo-o-conceito/

2

What are Hooks?

Hooks are functions, so they vary so much from each other. Some return an object, others return an array, a function or nothing. Each hook will have your responsibility, including you can create your own. Examples of some Hooks react:

  • useState: Returns a state value and a function to update it. Equivalent to state of the class components.

  • useEffect: Performs a function after the component is rendered on the screen. It is possible to define whether it will be executed only in the first rendering, in all, or when some variable is updated. It is like the componentDidMount or componentDidUpdate of the class components.

  • useContext: It makes use of a context shared between different components. It’s like the static contextType = MyContext or <MyContext.Consumer> of the class components.

  • useRef: Returns a reference to a mutable value. Can be used to store ref of elements in the DOM.

There are several others Hooks, I mentioned these briefly only to give examples that their behaviors are quite distinct, and that it is possible to perform class component things into functional components.

As use Hooks?

The Hooks can only be used in functional components. At each render, the hook runs again, since you are invoking it in your component, for example:

function Component() {
  // O hook abaixo é o useEffect, e estou invocando ele passando dois argumentos,
  // uma arrow function e um array vazio.
  useEffect(() => {}, []);
}

And here comes an important point. It’s not because the hook is invoked in every surrender that necessarily something will be done. Some Hooks make use of an array of dependencies to know if they should run something again (see What is and why should I provide a "dependency array" for React’s Hooks?).

Others, do not need the dependency array, as they do not execute any different code in the second render on, is the case of useState, that accepts only the initial state and returns the current value and a function to update the value:

function SubComponent({ current }) {
  const [childCounter] = React.useState(current);

  return (
    <div>
      <p>childCounter: {childCounter}</p>
      <p>O <b>childCounter</b> não atualiza porque apenas passo o valor inicial para o hook useState, mesmo sabendo que a prop current possui o valor {current} :)</p>
    </div>
  );
}

function App() {
  const [parentCounter, setParentCounter] = React.useState(0);

  function increment() {
    setParentCounter((oldCounter) => oldCounter + 1);
  }

  return (
    <div>
      <p>parentCounter: {parentCounter}</p>
      <SubComponent current={parentCounter} />
      <button onClick={increment}>Incrementar</button>
    </div>
  );
}

ReactDOM.render(<App /> , document.querySelector("#app"));
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"></div>

What are the Hooks? Why do they exist?

Here is worth reading from official documentation, which is quite complete on the subject. In short, they were created to:

  • Allow you to reuse state logic without changing its component hierarchy;
  • Allow you to divide a component into smaller functions based on the related parties (such as fetching data);
  • Classes are confusing, and Hooks allow you to use more React features without classes.

I’ll tell you more about that in the question The "Class Components" died in React?

Rules

The Hooks have some rules well defined. They must be executed:

  • Only in the top level. That is, do not execute Hooks within nested bonds, conditions or functions;
  • Only in functional components.

In addition, the Hooks customized, created by you, should start with use. For example: useShortcut, useRequest, useAuthentication.


Other questions

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

Well, now you can use only functional components, without needing more components classes. This has apparently become a standard nowadays, it is very difficult to find any library that is updated and that uses classes (or that creates new code with classes).

But you can continue to do things only with class components. The documentation says that you have no plans to end classes. Again, I refer to the question The "Class Components" died in React?

Even, there is a question in FAQ, in free translation:

I need to rewrite all my class components?

No. There are no plans to remove classes from React - we all need to continue developing projects and we cannot afford the rewrites. We recommend trying Hooks in new codes.

And also in Strategy of Gradual Adoption, where they recommend to avoid any "big rewriting", mainly in complex class components.

The community seems to have enjoyed, what are the reasons?

Everyone has their reason. Overall, I believe the documentation has listed the points in the topic well Motivation. They are simpler to understand than classes, for those who are not used to; you can reuse logic with state; they have a standard work well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.