Basic Hooks in React

We explored what hooks are and how they work in the last post. This article, on the other hand, will focus on Basic Hooks in React and some real-world examples and explanations of React’s fundamental hooks.

Hooks have performed a variety of functions since their introduction in React. Let’s start with a discussion of the advantages of hooks.

Advantages of Hooks in React

  • Easier to test and work with
  • They don’t have to negotiate HOCs (Higher Order Components) ,render props, children as functions, and classes.
  • Hooks make code more understandable and provide separate (and isolated) concerns.
  • Better code modification – Because Hooks are function. Code change is considerably easier, as functions in JavaScripts are much easier to modify than classes.
  • Hooks also prevent code from being repeate between lifecycle methods and components.

The benefits listed above are only a few of the numerous benefits available. Let’s get to the meat of this discussion, which is React’s Basic Hooks.

In general, React hooks are divide into numerous categories, including 03 Basic and 07 Additional Hooks. The basic Hooks of React will be discuss here.

Basic or Fundamental Hooks in React

When dealing with React, there are three (03) fundamental Hooks to employ. They are as follows:

  1. useState
  2. useEffect
  3. useContext

useState()

Hooks State, also known as useState Hooks, is a new way of expressing a state in a React app. Hook sets and retrieves state using the useState() functional component. The returned state (state) during the initial render is the same as the value passed as the first argument (initialState). It can be declare as:

const [state, setState] = useState(initialState);

The state updates using the setState function. It receives a new state value and re-renders the component in the background. The setState method can be use by the user/developer in the following ways:

setState(newState);

Prerequisite

Before utilizing the setState method, you must first import useState from React. You can do so by following these steps:

import React, { useState } from 'react';

Let’s look at an example to better grasp Hook State:

import React, { useState } from 'react';  

function CountApp() {  
  // Declare a new state variable, which we'll call "count"  
  const [count, setCount] = useState(0);  

  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default CountApp;  

Output:

react1

In the example above, useState is the Hook that must be call from within a function component in order to add some local state to it. The useState function returns a pair, with the first element being the current state value/initial value and the second being a function to change it. Then, from an event handler or someplace else, we’ll call this method. This is identical to the useState. In the class, setState uses. Without Hooks, the similar code looks like this:

import React, { useState } from 'react';  

class CountApp extends React.Component {  
  constructor(props) {  
    super(props);  
    this.state = {  
      count: 0  
    };  
  }  
  render() {  
    return (  
      <div>  
        <p><b>You clicked {this.state.count} times</b></p>  
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>  
          Click me  
        </button>  
      </div>  
    );  
  }  
}  
export default CountApp;  

useEffect()

The Effect Hook is the most basic hook in React after State Hooks. Effect hook enables us to implement side effects (inaction) in functional components. It does not take advantage of the component lifecycle methods offered in the component class. It was similar to utilising componentDidMount(), componentDidUpdate(), and componentWillUnmount() lifecycle functions before Hooks were introduce. Web developers may utilize useEffects() to help their web application conduct activities in a seamless manner. For example:

  • Updating the DOM
  • Getting data from a server API and consuming it
  • Creating a subscription, and so forth. In other words, useEffect takes a function and uses it to create an effect in the function.
useEffect(
    () => {
        const subscription = props.source.subscribe();
        return () => {
            subscription.unsubscribe();
        };
    },
    [props.source],
);

Note: If you only want the function to run once, the second parameter can be an empty array.

Let’s look at a longer and more helpful chunk of code to better understand how to utilize useEffect (). But first, we must import useEffect from React, just like we did with useState. Consider the following example:

import React, { useState, useEffect } from 'react';

Let’s look at an example to better grasp the Hook Effect:

import React, { useState, useEffect } from 'react';  

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

  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {  
    // Update the document title using the browser API  
    document.title = `You clicked ${count} times`;  
  });  

  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default CounterExample;  

Output:

react2

The above-coded example is a continuation of the previous useState() example with the addition of a new feature that changes the document title to a custom message that includes the number of clicks.

In React, there are two sorts of effect hooks:

  • Effects without Cleanup
  • Effects with Cleanup

These two sorts of effect hooks will be discussed in the next post click the link to know more How to create a custom hook in React.

useContext()

useContext takes a context object as input, which is the value returned by React.createContext and returns the context’s current context value. When the context value changes, a component using useContext will always re-render.

In other words, the useContext() hook is used to create shared data that can be accessed throughout the component hierarchy without having to feed props down to each level manually. Without the use of “props,” the context defined will be available to all child components.

Before we go into the useContext example, let’s look at an example code that doesn’t use useContext, i.e. with the Consumer component (the hard way):

import React from "react";
import ReactDOM from "react-dom";

// Create a Context
const NumberContext = React.createContext();
// It returns an object with 2 values:
// { Provider, Consumer }

function App() {
  // Use the Provider to make a value available to all
  // children and grandchildren
  return (
    <NumberContext.Provider value={42}>
      <div>
        <Display />
      </div>
    </NumberContext.Provider>
  );
}

function Display() {
  // Use the Consumer to grab the value from context
  // Notice this component didn't get any props!
  return (
    <NumberContext.Consumer>
      {value => <div>The answer is {value}.</div>}
    </NumberContext.Consumer>
  );
}

ReactDOM.render(<App />, document.querySelector("#root"));

Let’s take a look at what just happened:

To begin, we construct a new context and save it in NumberContext. This is a two-property object: Provider and Consumer. They’re a matched pair that are born with the ability to converse with one another (but not with other contexts).

The NumberContext is then render. Provide a value prop to a provider with some content. This value will be pass on to all of its offspring and their descendants. The Consumer (or useContext) will be able to read out the value for the whole subtree.

Finally, we use the Consumer component within the Display component to read the value.

useContext() code example:

Without a Consumer, useContext() allows you to “USE” context. Let’s utilize the useContext hook to rebuild the Display component:

// import useContext (or we could write React.useContext)
import React, { useContext } from 'react';

// ...

function Display() {
  const value = useContext(NumberContext);
  return <div>The answer is {value}.</div>;
}

Use the context object you acquired from React to call useContext(). createContext, and the value appears. Wasn’t it simple? The only thing to keep in mind is that useContext requires the entire context object, not just the Consumer! (This is why I didn’t immediately destructure the Context object) The nice part about React is that it will notify you if you forget.

So that was the conclusion of this article. The varieties of useEffect() will be cover in the upcoming post, and we’ll try to go deeper into the fantastic and very cool world of React. click the link to go for the next article How to create a custom hook in React.

If you want to know more about react then please visit React official documentation.

Leave a Comment