React Hooks for Beginners. What are React Hooks for?

React Хуки

React Hooks are required to keep your project clean. React was introduced to the world about 5 years ago and to this day retains its status as one of the most used JS front-end libraries. React is so popular that I have earned + 132,000 stars on GitHub right now while writing this article.

The basic concept of react is component based. This will allow you to write reusable codes and keep your project clean. As you know, there are 2 types of components in React: class-based and functional components. Class-based components are slightly older than functional components.

But functional components are cleaner, faster than classes. So React introduced hooks. Hooks are what allows you to write functional components and still connect and use class-based functions. Thanks to React Hooks, we are able to write much cleaner and simpler components using functions, and we still have great class-based component capabilities such as state and stateful logic in our arsenal!

Why should we use React Hooks and functional components?

If you go through the documentation yourself and read about hooks and functional components, you will have no doubts about using them. But let me keep things simple – I’ll show you some real-world examples, and we’ll work together on the reasons for use, and as a bonus, we’ll save you time in the future.

As the first reason, I will note that the code is smaller and cleaner, we want to create a component that displays the title and subheading. Here’s an example of writing by class:

class Header extends React.Component{

render() {

return(</pre>
<div>
<h1>Title</h1>
<h4>Subtitle</h4>
</div>
<pre>);

}

}

Now let’s take a look at an example of a functional component:

const Header = () => (</pre>
<div>
<h1>Title</h1>
<h4>Subtitle</h4>
</div>
<pre>);

It’s obvious which one is cleaner, isn’t it?

Hierarchy and stateful logic

As mentioned in the documentation (https://reactjs.org/docs/hooks-intro.html), unfortunately, React does not have the ability to “attach” reusable behavior to a component (for example, connecting to a store). What does it mean? Imagine 3 components, each containing a form and each form containing a name. You store the value of your input in the state of these components. So you have 3 class-based components with state (including name) and handleNameChange handler. And so, you start writing the same code over and over, every time you want to use the name field in your project.

But down with this masochism – just use hooks! Write one hook and import it into any functional component so you can use the name and behavior of its handler.

 

React Hooks – third reason to use

Are class based components tricky? Definitely damn it! When you want to write a class-based component, you need to understand the basic concepts of the word “this”, life cycles such as componentDidMount or componentDidUpdate, and the like. Meanwhile, in functional components, people just work with functions! Special arrow functions. Not only is “this” and binding missing, but also state and lifecycle! But what if we want to get the API after mounting our component or, for example, have forms and perform validation and something with their value in the state? Are you worried? Do not worry so much, everything is simple. You can always use useState hooks instead of states and setState and Effect instead of lifecycle methods.

Definition of useState

Now let’s give time for a few more simple practical examples, this time to answer the question: how are we going to work with useState in react?

import React, { useState } from 'react';

function Example() {

// Declaring a new state variable "count"

const [count, setCount] = useState(0);

return (</pre>
<div>You have pressed {count} times <button> setCount (count + 1)}></button> Click me!</div>
<pre>);

}

This is a sample React documentation for useState and counting from zero on button click. The class code type is here too:

class Example extends React.Component {

constructor(props) {

super(props);

this.state = {

count: 0

};

}

render() {

return (</pre>
<div>You have pressed {this.state.count} times <button> this.setState ({count: this.state.count + 1})}> </button> Click me!</div>
<pre>);

}

}

You can see useState (), count, setCount and some brackets here.

UseState ():

This is a function provided by the React team in the React library and should be imported first. UseState () returns an array whose argument is the initial state value.

Count:

This is the name of our variable in the state.

SetCount:

This is the function that implements our stateful logic. The setCount value is the new value for our state.

Brackets:

But this is already a simple array destructuring. As I mentioned above, each useState () returns an array. So, using this bracket, we are using the first array value ([0]) as our state value, and the second ([1]) is the method we define to change our state. Therefore, here we are saying that our component has a state that includes a counter, and we want to handle its changes using the setCount method.

Some useState examples and our own hooks

Now I will show you a useful implementation of useState. In this example we are modeling hooks using useState, so you can see the reusability and flexibility of hooks here as well. Let’s take as a basis the fact that we want to have a counter that will have a start, step, count and end when the button is pressed. This is the main component:

export const CounterDemo = () => {

const [count, handleCount] = useCounter(100, 130,5);

return (</pre>
<div>{count} <button>Count</button></div>
<pre>);

};

Note that useCounter is a custom hook that takes the same 3 arguments: start, finish and step.

Destructuring our array means that the hook returns an array, the first element of which is the value of count and the second is the state change method (our state logic). We use this arbitrarily named handleCount method as our onClick event handler.

Now it’s time to see our own Hook implementation:

import {useState} from 'react';

export const useCounter = (start, finish, step) => {

// Our condition

const [count, setCount] = useState(start);

// handleCount condition

const handleCount = () => {

if (count === finish) {

return setCount(start);

} else {

return setCount(count + step);

}

};

//Return our custom hook array

return [count, handleCount]

};

All this code can be conditionally divided into three parts:

  1. Defining our state: We have a variable count in our state, the initial value of which is equal to the value “start”, and we want to change this state using the setCount method.
  2. The handleCount method implementation. Using the condition to check whether we have reached the final amount or not, the setCount method gets down to business to change the count value in accordance with the result of the if condition.
  3. Returning our custom hooks array: as you can see, the first is the count value and the second is our handleCount method.

React Hooks – why should you use them?

Everything in this article is a basic and core concept of React hooks for newbies and developers who are afraid of change. You can read more about the use of hooks in the React docs and elsewhere.

But! Hooks are optional. The React team is not putting any pressure on you to port and / or convert your code to use hooks.

Also, for a deeper look at the performance of functional and class-based components, you can read Philippe Leo’s excellent article: “React Functional Components Are 45% Faster, Now” https://medium.com/missive-app/45-faster-react-functional-components-now-3509a668e69f

And as the icing on the cake, I highly recommend that you familiarize yourself with some of the important rules for using hooks in this article in the official docs: Rules of Hooks https://reactjs.org/docs/hooks-rules.html

Having studied hooks in full, you will certainly know their power and indispensability in writing React projects.

Engineer Programmer IMTO. Specialist in web and software development, data science, creative concept, Agile & Scrum methodology.

0 0 голос
Rate article
Подписаться
Уведомить о
guest
0 Comments
Межтекстовые Отзывы
Посмотреть все комментарии
error: Контент защищен от копирования!
This site uses cookies to improve your browsing experience. Your personal data is safe