Trending News
If you're looking to add more functionality to your functional components, the Hooks API is a great place to start.

Fetching Data and Updating State with Hooks

The componentDidMount() lifecycle method provided by every React class component was discussed in detail. However, many parts are not implemented as classes. This is probably due to the fact that classes are not yet universally supported by browsers, necessitating the usage of transpilers like Babel or TypeScript to convert your code into a form that modern browsers can understand.

Functional components are those that are not formed from a class but instead are declared as regular functions. A functional component in React lacks access to the standard lifecycle methods available to classes. Furthermore, they do not have their own sovereign nation. setState(…). Therefore, it is possible that you will need to learn how to get data and re-render the component.

As a React developer, you should know How to fix “The useState set method not reflecting a change immediately”.

 

Introducing Hooks

Since version 16.6 of React, functional components may maintain their own state and initiate their own lifecycle processes independently. Hooks, a new feature in React, makes this kind of functionality doable.

To access the lifecycle characteristics of a component from a functional component, you can use “hooks,” which are functions that begin with the word use.

Ten preexisting hooks are at your disposal, with useState and useEffect being the most frequently employed.

useState

The documentation suggests that the useState hook is analogous to the this.setState() function in class components, minus the merging of the old and new states. The state value and an update function are provided via the useState hook.

 

import React from ‘react’;

function BooksList () {

const [books, updateBooks] = React.useState([]);

}

 

You can see how the useState hook is implemented in the aforementioned example. A global variable named books is declared and initialised to an empty array. Although the syntax for array destructuring may appear daunting at first glance, you are still free to give your state variable and updater function meaningful names. State changes can be made by calling the updater function:

 

function BooksList () {const [books, updateBooks] = React.useState([]);

const handleClick = () => {

// update the books state property by adding a new book

 updateBooks([…books, { name: ‘A new Book’, id: ‘…’}]);

}

return (

  <ul>

   books.map(book => (

     <li key={book.id}>{book.name}</li>  

        ));

  </ul>

);

}

This new array of books will be passed as the only input to the updater function called updateBooks, which will be run whenever the handleClick method above is invoked. The component will re-render with the new value of books after the books property is updated.

useEffect

The useful useEffect hook is available when you need to perform side effects in a functional component. Using the Effect Hook, you can add in-function effects to sub-functions.

 

The useEffect hook requires a function and a dependency list as input. If there is a change to the function or its dependencies, it will be invoked.

 

function BooksList () {   const [books, updateBooks] = React.useState([]);

   React.useEffect(function effectFunction() {

       if (books) {

           updateBooks([…books, { name: ‘A new Book’, id: ‘…’}]);

      }

   }, []); // This empty array represents an empty list of dependencies

   …

The useEffect hook is presented above with no initial dependencies. This hook will therefore only execute once, during the component’s initialization. Since there are no dependencies to monitor, it will never execute at any other time.

The componentDidMount() lifecycle method from a class component is nearly equivalent to using an empty array.

What happens if a value is provided for the dependency array is demonstrated in the following example.

 

function BooksList () {

   const [books, updateBooks] = React.useState([]);

   const [counter, updateCounter] = React.useState(0);

   

   React.useEffect(function effectFunction() {

       if (books) {

           updateBooks([…books, { name: ‘A new Book’, id: ‘…’}]);

       }

   }, [counter]);

   

   const incrementCounter = () => {

       updateCounter(counter + 1);

   }

 

The effectFunction is invoked in this case during component initialization and whenever the counter variable is modified.

Common practise when utilising the useEffect hook is to evaluate it in relation to all of the class component lifecycle methods. Rather, you should picture the useEffect hook in terms of how you want your state to look after you’ve altered specific variables.

Here are a few guidelines for properly use the useEffect hook:

  • Hooks must be invoked in the same sequence in which they were defined, and cannot be used inside of conditionals.
  •  A conditional around the useEffect could break the loop; the function passed to the hook must not be async, as promises are always returned by async functions and the useEffect method must either return nothing or a cleanup function.

Ending

If you’re looking to add more functionality to your functional components, the Hooks API is a great place to start. Use the useEffect hook to take care of unintended consequences, including writing to a log file, performing an asynchronous call, or saving a value to local storage. For functional components, the useState hook allows you to provide state without resorting to a class component. More hook features, such as how to make your own custom hooks, will be detailed in a subsequent tutorial.

Using a class component, you may easily update the component’s state and re-render it.

Share via:
Sponsored Post
No Comments

Leave a Comment