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 : 5985  
 
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

Dates in local format with Javascript

In the articles we have about dates in JavaScript we were missing one about how to create dates in local format with JavaScript. That is to say, being able to…

Formatting hours in Javascript

Continuing with the set of articles that talk about internationalisation elements, like the previous one where we talked about relative dates in JavaScript, we will see in this one how…

Request data with prompt in JavaScript

After having published several articles about how to manipulate arrays and dates, today I will publish a post that some of you will find too basic and others will find…

Relative dates in JavaScript

One of the interesting things about the internationalisation library represented in the Int object is the handling of relative dates in Javascript. This handling allows us to represent a date…

How to access webcam and grab an image using HTML5 and Javascript

We often use webcams to broadcast video in real time via our computer. This broadcast can be viewed, saved and even shared via the Internet. As a rule, we need…

The JavaScript forEach loop

We have already talked about how to handle some of loops  types in Javascript including for, for-in and for-off loops. In the case of today we are going to see how…

Flattening arrays in JavaScript

When we are handling arrays that are arrays or have multiple dimensions it can be very useful to know how to flatten arrays in JavaScript. That is to say, to…

How to populate an array with random numbers in JavaScript

Some of you might think that what we explained in the article on how to populate an array with numbers, apart from the didactic part, would not have much applicability…

How to populate an array with numbers in JavaScript

Populate an array with numbers in JavaScript The first step is to initialise the array. So today we are going to see a simple way to do it and see how…

Top Javascript Libraries and Frameworks Part 2

What are JavaScript frameworks?   JavaScript frameworks are application frameworks that allow developers to manipulate code to meet their particular needs. Web application development is like building a house. You have the option…

How to Send Email from an HTML Contact Form

In today’s article we will write about how to make a working form that upon hitting that submit button will be functional and send the email (to you as a…

Top JavaScript libraries and frameworks part 1

JavaScript libraries and frameworks make it easy to develop websites and applications with a wide variety of features and functionality, all with dynamic, flexible and engaging features. According to a 2020…

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