how to use react hooks

How to use React hooks in functional components

React hooks are new addition to react 16.8. Hooks help developers to use state and life cycle methods without writing a class. Hooks do not work inside class components instead, It helps us to use the class features without actually writing a class component. Here in this guide, we’ll discuss adopting react hooks to write components that are fairly easier to write and use.

As you may already know there are two methods to develop a component in React. Either we can use a class-based component or functional-based which are stateful and stateless respectively.

Earlier we had to use class-based components to use component life cycle methods and states inside the components. Now React released a new concept of hooks to make use of state and life cycle methods inside functional components.

React hooks are the latest addition to the react but there is no need to absolutely re-write your class components as React doesn’t have any plan to drop class-based components. Instead, we can make use of hooks while writing a new component.

The useState hook

useState hooks allow us to make use of state variables inside the functional components. Let’s see the implementation of state variable using useState API also we’ll discuss the same for class components.

import React, { useState } from 'react';

function Counter(){
    const [ counter,setCounter ] = useState(0);
    return(
       <div>
          <p>Value of count is {count}</p>
          <button onClick={ () => setCount(count+1) }>Update</button>
       </div>
    )
}

Here as you can see we are importing useState hook from react to make use of state inside the functional components. useState hook declares inside a const and uses the ES6 array destructuring syntax.

To declare a count state variable we used const [count, setCounter ] = useState(0). Here count is actual state variable and setCounter is a function to update the counter and initialised the count variable with value 0.

Now let’s see how we are doing this inside a class based component.

import React, { Component } from 'react';
class Counter extends React.Component{
   constructor(props){
      super(props) 
   }
   this.state = {
       count:0
   }
   render(){
      return(
         <div>
          <p>Value of count is {count}</p>
          <button onClick={ () => this.setState({count:count+1}) }>Update</button>
       </div>
      )
}

The useEffect hook

Imagine you have a perfectly working functional component and you want to use lifecycle methods without converting it into a class component. There we’ll use useEffect hooks. These are basically the alternative to component lifecycle methods in-class component such as componentDidMount and componentDidUpdate.

Example:

import React, { useEffect, useState } from 'react';
import Post from './Post';
const PostList = () => {
  const [posts, setPosts] = useState([]);
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts')
      .then(response => response.json())
      .then(data => {
        setPosts(data);
      })
  });
  return (
    <div>
      {
        posts.map(post => (
          <Post
            key={post.id}
            title={post.title}
            completed={post.author}
          />
        ))
      }
    </div>
  )
}
 
export default PostList;

useEffect API is much useful when we want to update the DOM just after mounting it or to update the DOM frequently. But, If you run the above code you can see it’s updating after each render. To avoid this we can pass an optional array as a dependency to run only in the first render.

useEffect(
    () => {
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then(response => response.json())
        .then(data => {
          setPOsts(data);
        })
    },
    []
);

Conclusion

That was how we can implement React hooks in functional components. They provide a much cleaner and efficient way to create components in React applications. Although they are better than class components they do have some limitations such as we can’t use hooks inside regular JavaScript functions and we are limited to call hooks only at the top level of the functions.

Thanks for reading! feel free to share with other fellow developers. If you are interested to know the differences between Expo workflow and React Native bare workflow read the article below.

Leave a Comment

Your email address will not be published.