What are React Hooks and what problems they solve

by Janeth Kent Date: 13-05-2021 javascript react


Working with React, - and before the release of Hooks in version 16.8 -  there was always the possibility to create components in three different ways based on a number of suspects and needs:

1. Elementary components - These components are the simplest ones, they are characterized by being mere variables that store a specific JSX expression, so they do not receive properties and have no state, although they can still use any operator as usual, for example:

 
const componentname = list.length > 1 ?        
    [            
      <li className="my-class">{list[0]}</li>,            
      <li className="my-class">{list[1]}</li>        
    ]      
   :      
   null;
 

This array injected into a JSX <ul> tag will render that list in our DOM.

2. Functional Components - In the pre-Hooks era, these components were primarily used to isolate potentially reusable features but with additional logic not dependent on their state, as functional components received properties but did not possess state. An example of a functional component would be:

 
function MyComponent(props) {
    return <h1>This component returns: {props.value}</h1>
}
// We can render it directly
const myComponent = <MyComponent value="Exactly this"/>
ReactDOM.render(
    myComponent,
    document.getElementById('root')
);
 

3. Class components - These have always been the most common components in React development, for the simple fact that they were the only ones with properties, state and lifecycle, making them essential for managing the main logic and cycle of the application. The simplest example of a class component with state and with some life cycle would be:

 
class MyComponent extends React.Component {      
          constructor(props) {         
           super(props);         
           this.state = {             
           value: ''         
           }      
          }      
          componentDidMount() {          
                 this.setState({ value: 'This one' })      
          }      
          render() {          
          const { value } = this.state;          
          return <h1>This component returns: {value}</h1>      
          } 
     }
 

However these assumptions were rendered obsolete when React introduced hooks in 2018, promising a new way of working based on functional components with access to state and lifecycle.

 

What is a Hook?


A Hook is a javascript function that allows to create/access React state and lifecycles and that, in order to ensure the stability of the application, must be used following two basic rules:

Must be called at the top level of the application - A hook should never be called inside loops, conditionals or nested functions, as the calling order of hooks must always be the same to ensure that the result is predictable during rendering. This top-level-only usage is what ensures that React's internal state is correctly preserved between different calls of the same hook.

Must be called in functions or other custom React hooks - A hook should never be called outside of a React function or other custom hook, so that the component's state logic is clearly visible from the rest of the code for the scope set by React.

As we saw in the previous section, a functional component before React 16.8 could not have state or life cycle, so the only way to create, for example, a simple accumulator would be:

 
class Acumulador extends React.Component {      
               constructor(props) {         
                     super(props);         
                     this.state = {             
                     count: 0         
                     }     
                }      
                  render() {          
                  const { count } = this.state;          
                  return (              
                       <h1>The button has been clicked { count } times</h1>              
                       <button onClick={() => this.setState({count: count + 1})}>Click me</button>                       )      
                  } 
                }
 

However, thanks to hooks we can now replicate this component by adding a state with the use of useState, so that the previous accumulator in a functional way would be:

function Acumulador(props) {      
         const [count, setCount] = useState(0);      
         return (          
           <h1>The button has been clicked  { count } times</h1>          
           <button onClick={() => setCount(count => count + 1)}>Click me</button>      
           );  
      }
 

Hooks in React

 

As the ultimate purpose of hooks is to simplify the actual logic, React provides only a reduced set, with the flexibility to respond to various situations in the lifecycle of an application and the possibility to build our own as well.

 

Basic Hooks

 

React provides three basic hooks that meet the usual needs for implementing a lifecycle in a class component:

 

Hook of "state" useState

 

This hook returns a value with a maintained state and a function that is necessary to update it:

const [count, setCount] = useState(0)
 

The initial state is the parameter passed to useState, in this case 0, and it will be the state during at least the initial rendering and until the function setCount is called with a new value, so that in this case, for example, setCount(count + 1) will increase the value of count by one, becoming 1 in the next rendering.

It is also possible to use the value of the previous state within the state setting function itself, so the above is also possible to write it as setCount(count => count + 1).

 

Hook of effect useEffect

 

This hook allows us to add side effects to a given functional component, that is, it allows us to make modifications to our logic once the rendering has been performed, in the same way as the componentDidMount,componentDidUpdate and componentWillUnmount lifecycle methods in class components.

One of the great advantages of this hook is that it simplifies the life cycle, so that the three available class methods can be expressed using only this hook. For example, in the case of a class component that loads a set of data from a cookie on mount, and writes it on unmount, we could write it like this:

 
 
class LoadUnload extends React.Component {        
     constructor(props) {            
        super(props);            
        this.state = {                
         data: null            
        }        
     }        
     componentDidMount() {            
        // theoretical function that returns cookie data as a js object            
        const loadedData = getCookie('data');            
        this.setState({data: loadedData})        
     }        
     componentWillUnmount() {            
        const { data } = this.state;            
        // Theoretical function that saves the data object in JSON format            
        setCookie(data);        
     }    
}
 

This could be done in the functional component using a single functional component:

 
 
function LoadUnload(props) {        
    const [data, setData] = useState(null);        
    useEffect(() => {            
      const loadedData = getCookie('data');            
      setData(loadedData);            
      return () => setCookie(data);        
   }, []);    

}
 

Where, by using an empty array of dependencies, we tell the effect to run only on mount (Like componentDidMount) and the return of the function is a new function that is called only on unmount (Like componentWillUnmount).

 

Context Hook useContext

 

If you have ever used React context, this is the hook you need. A context in React is a way to pass data between different components without the need to manually cascade props. Something useful, for example, when we want to create themes or locations, which must be global for the entire component tree and it can be cumbersome to have to propagate them for each added component.

In the case of class components, the context is passed through a provider that encompasses the tree of components that must have that context, so that a component that has localization and uses a LocalContext context can be written like this:

 
import {LocalContext} from './local-context';    

    class LocalizedText extends React.Component {    
       render() {      
         let local = this.context;      
         return (        
           <div          
             {...this.props}        
             >              
               <h1>{local.title}</h1>              
               <p>{local.paragraph}</p>        
           </div>      
        );    
      }  
}  
LocalizedText.contextType = LocalContext;    
export default LocalizedText;
 

In the case of a functional component, and with the use of hooks, we can use useContext that allows us to access the created context, for example for a small application that passes the location to a component like the previous one but in a functional way:

 
const local = {    
    en: {      
     title: 'Hi',      
     paragraph: 'This is a little test'    
    },    
    es: {      
     title: 'Hola',      
     paragraph: 'Esto es un pequeño ejemplo'    
    }  
};    

const LocalContext = React.createContext(local.es);  
  
function App( ) {    
  return (      
   <ThemeContext.Provider value={local.en}>        
     <Container />      
   </ThemeContext.Provider>    
  );  
}  
  
function Container(props) {    
  return (      
    <div>        
      <LocalizedText />      
    </div>    
  );  
} 
   
function LocalizedText(props) {    
  const local = useContext(LocalContext);    
  return (      
   <div {...props}>          
    <h1>{local.title}</h1>          
    <p>{local.paragraph}</p>        
   </div>    
  );  
}
 

 

Additional Hooks

 

In addition to these Hooks, there are a series of hooks oriented to the optimization of our rendering flow, to avoid losing cycles, such as useCallback and useMemo, whose purpose is to memorize functions and functional components to not render them uselessly if none of their dependencies has changed (As when we implement the life cycle shouldComponentUpdate in class components).

However, about these hooks and others we will see more information about their application in the next part where we will see a practical example in which to apply all this knowledge.

 

Why use Hooks?

 

The use of hooks in functional components seems to be a mere addition that, in fact, does not replace and is not intended to replace the current class components, so we could ask ourselves:

What is the point of using hooks and changing our way of developing with React?

First of all, as Dan Abramov said in the presentation of this feature, the use of hooks reduces the number of concepts needed in the development of React applications, so that we do not need to continuously switch between functions, classes, HOCs or elements to perform similar tasks; hooks offer us homogeneity in the ecosystem.

Secondly the React lifecycle has been greatly simplified with the use of hooks , so that, as we saw earlier, the lifecycle methods of classes componentDidMount, componentDidUpdate and componentWillUnmount are summarized in a single hook useEffect that acts as all three. Thus a timer that adds a certain amount per second, using a class component first:

 
class Timer extends React.Component {      
   constructor(props) {          
     super(props);          
     this.state = {              
       seconds: 0          
     }      
   }      
   componentDidMount() {          
     const {seconds, quantityToAdd} = this.state;          
     this.interval = setInterval(() => {              
     this.setState({seconds: seconds + 1})          
     })      
   }      
   componentWillUnmount() {          
     clearInterval(this.interval);      
   }      
   render() {          
     return (              
        <div>Han pasado {this.state.seconds} segundos</div>          
     )      
   }  
}
 

It can be expressed as a functional component with the use of hooks:

 
function Timer(props) {      
  const [seconds, setSeconds] = useState(0);      
  useEffect(() => {          
    const interval = setInterval(() => {              
      setSeconds(seconds => seconds + 1);          
    }, 1000);          
    return () => clearInterval(interval);      
  },[]);      
  return <div>Han pasado {seconds} segundos</div>;  
}
 

It is undoubtedly much more compact, both in code quality and use of functions, and the operation is similar.

Thirdly, using functional components reinforces React's basic principle of avoiding mutations, since changing the state of a class component is the same as mutating its state property, just as it is necessary to perform a binding for functions that manage events, approaches that significantly increase the complexity and reduce the predictability of the component.

And finally we find that the introduction of the hook useReducer introduces in the React core the possibility of working with a Redux pattern without the need of additional dependencies. This hook, cataloged in the category of "additional hooks", is always recommended when the state of the application is too complex and with a large amount of nesting, since the reducer accepts a function of type (state, action) => newState returning the current state and a "dispatch" function, which allows us to emulate the functionalities currently available in the redux and react-redux libraries so often used to solve the problem of state management or property cascading.

 

To continue

 

React Hooks offers us a new paradigm, and a new way of thinking, that is closely related to functional programming, where functionalities are predictable input-output blocks and are considered first class citizens and side effects are isolated in a highly controllable way.

However, to possess the theoretical knowledge is not to possess the mastery of its application, therefore in the following part on Hooks we will develop a small incremental game with the use of hooks, making a special emphasis on the application flow, the translation into components and hooks for the life cycle and additionally the use of optimization hooks to improve performance (Like the already mentioned useCallback and useMemo).

 
by Janeth Kent Date: 13-05-2021 javascript react hits : 6846  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

Related Posts

Difference between arrow and normal functions in JavaScript

In this tutorial we are going to see how arrow functions differ from normal JavaScript functions. We will also see when you should use one and when you should use…

JavaScript Arrow functions: What they are and how to use them

In this article we are going to see what they are and how to use JavaScript Arrow Functions, a new feature introduced with the ES6 standard (ECMAScript 6). What are Arrow…

How to insert an element into an array with JavaScript

In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript. For this we will use the splice function. The splice function will not…

What is the difference between primitives types and objects in JavaScript?

In this short tutorial we are going to look at the differences between primitive types and objects in JavaScript. To start with, we're going to look at what primitive types…

How to get DOM elements with JavaScript

When you access any element of the DOM, it is usual to save it in a variable. This is something that at first might seem very simple, but if you…

How to reverse an array in JavaScript

In this tutorial we are going to see how you can change the order of the elements of an array so that they are inverted. You could use a loop…

How synchronize the scroll of two divs with JavaScript

In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example,…

How to use the codePointAt method in JavaScript

The JavaScript codePointAt method has more or less the same function as the charCodeAt method, used to get the 16-bit Unicode representation of the character at a certain position in…

How to check if a value is a number in JavaScript

In this short tutorial we are going to look at the various methods that exist to find out if a value is a number in JavaScript.   1. Using the isNaN() function   One…

How to use the charCodeAt method in JavaScript

The charCodeAt method is accepted by strings in JavaScript, returning the 16-bit Unicode code of the character at the position we pass as a parameter to the method. The charCodeAt method…

How to use the charAt method in JavaScript

The charAt method is accepted by strings in JavaScript, returning the position of the character passed as a parameter within the string. If the string contains multiple occurrences of the character…

Strings in JavaScript: What they are and how to use them

In this tutorial we are going to explain what strings are and how they are used in JavaScript. The tutorial is intended for people who are learning to program in…

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertisements related to your preferences. By clicking "Accept all" you agree to the storage of cookies on your device to improve website navigation, analyse traffic and assist our marketing activities. You can also select "System Cookies Only" to accept only the cookies required for the website to function, or you can select the cookies you wish to activate by clicking on "settings".

Accept All Only sistem cookies Configuration