React Hooks Guide for Beginners

React Hooks Guide for Beginners
Spread the love

As an experienced programmer, you have realized how Hooks have changed how you code in React. They have outdone the class components in handling lifecycles and states in React. Why not, given how concise and efficient this approach is? It explains why many developers are opting to use React Hooks.

That said and done, you need technical know-how to use this advantageous method. Doing so guarantees an easy time creating user interfaces using this incredible JavaScript library. To get started, here is a React Hooks guide to go with. Check it out!

What Are React Hooks?

First, it is good to mention that these React Hooks didn’t exist until February 2019. It happened during the release of React 16.8, which integrated a new API known as Hooks. It marked the beginning of using features such as state without writing classes. Since then, it has become relatively popular in the React industry. Programmers use it when working on production apps and open-source projects.

Since the React 16.8 release, developers have used React Hooks API to make app development easy and quick. Hooks are completely opt-in; hence possible to try them in several components and not rewrite the existing code. Their lack of breaking changes makes them compatible 100% backward.

Key Rules for React Hooks

As you create React Hooks, keep the following in mind

  • You can use Hooks to call other Hooks
  • However, you can’t call them from a regular JavaScript function
  • The only sources of the Hooks you can call are the React functional components, and you are at liberty to call Hooks from them
  • In the React hierarchy, Hooks are classified as your React function’s top level before introducing a return keyword
  • You should not call them inside a nested function, loop, or condition

Advantages of Using React Hooks

If you are on the fence regarding whether to learn React Hooks, here are some reasons you should start immediately.

  1. The Complexity of Class Components

Most developers find class components hard to understand. That doesn’t come as a surprise because of how large they are, not to forget the many operations they attempt to perform. Due to this complexity, it is often a challenge to understand them.

Fortunately, that stops being one of your concerns when using React Hooks. You are at liberty to separate any large component into several small functions. Forcing every logic into one class component is no longer necessary, thus solving the complexity issue.

  1. The Confusion Emanating From React Classes

It is often hard to learn React as it should because of classes. After all, using classes require you to master the working mechanism of this keyword. You also can’t afford to bind event handlers hence the need always to remember to do so constantly. React classes also lead to redundant methods, and all that sums up the confusion. Since React Hooks solve the problem of working with classes, you can see why shifting to it impacts your coding.

  1. React Hooks are readable

If you have used React classes, you can attest to the existence of a considerable amount of excess and redundant code. An excellent example is this counter-component.

class Counter extends Component {

constructor(props) {

super(props)

this.state = {

count: 1,

}

}

render() {

return (

<div>

The Current Count: {this.state.count}

<div>

<button onClick={this.setState({ count: this.state.count – 1 })}>

add

</button>

<button onClick={this.setState({ count: this.state.count + 1 })}>

subtract

</button>

</div>

</div>

);

}

}

 

You will be surprised to learn how short and readable a similar code, its equivalent for that mat, is if you use React Hooks and a functional component. It is as follows;

function Counter  ()  {

const [count, setCount] = useState(1);

return (

<div>

The Current Count: {this.state.count}

<div>

<button onClick={() => setCount(count + 1)}>add</button>

<button onClick={() => setCount(count – 1)}>subtract</button>

</div>

</div>

);

};

 

The comparison indicates that using React Hooks translates to short, easy, and readable code. Besides reading, maintaining such a code is a breeze. Unlike the class component, you don’t need to use constructors to initialize the state. Neither referencing this keyword constantly nor classes to extend React is necessary.

Other Benefits of Using React Hooks

As a developer, you have other reasons to use React Hooks, including the following;

  • Better code reuse
  • Improved defaults
  • Flexible movement either down or up the components tree
  • Improved code composition
  • Liberty to use custom hooks that share the non-visual logic excellently

The bottom line is React Hooks translates to neat work. Why not when using functional components is an option? It works with many things, if not everything, including handling logic or state and rendering user interfaces.

Most Commonly Used React Hooks

So far, there are about 10 built-in hooks. However, 4 of them are the ones commonly used, and they include;

  • useState() React hook
  • useEffect() React hook
  • useContext() React hook
  • useReducer() React hook

Let’s discuss the 4 in detail right away

  1. useState() React hook

Most programmers often use these React hooks. They introduce the hook for creating and managing state variables. If there is an update to a certain state variable, the change triggers the re-rendering of its respective component. Its syntax is as follows;

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

The useState React hook will take one optional argument, usually the state’s initial value. On the other hand, it returns an array comprising two values: its state variable and a function that updates that state.

The following counter component is an excellent exact.

  1. To begin with, you need to import the React hook as follows;

import { useState } from “react”;

 

  1. Next, introduce the initial value

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

 

  1. Add the rest of the code appropriately

 

import { useState } from “react”;

 

function Counter() {

// Declare a new state variable, which we’ll call “count.”

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

return (

<div>

Number of Sessions: {count}

<div>

<button onClick={() => setCount(count – 1)}>Add a session</button>

<button onClick={() => setCount(count + 1)}>Remove a session</button>

</div>

</div>

);

}

 

The above code renders a label Number of Sessions and figures 0 alongside it after the full colon, :. There are also two buttons, Add a session and Remove a session. Suppose you click the former repeatedly; the o changes to 1, 2, 3, 4, and so forth. If, after clicking Add a session the fourth time, you click the Remove a session button, the figure changes from 4 to 3 and will continue decreasing if you click it again and again.

  1. UseEffect() React hook

React developers often use lifecycle methods such as componentWillUnmount, componentDidUpdate, and componentDidMount. Using hooks combines the three methods, and you use them in functional components. That summarizes what UseEffect does.

Let’s look at an example

import { useState, useEffect } from “react”;

function Counter() {

// Declare state variables

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

const [session, setSession] = useState(“Chemistry”);

useEffect(() => {

console.log(`${session} will rule the world!`);

});

return (

<div>

Current {session}’s count: {count}

<div>

<button onClick={() => setCount(count + 1)}>Add session</button>

<button onClick={() => setCount(count – 1)}>Remove session</button>

Change Session:{” “}

<input type=”text” onChange={(e) => setSession(e.target.value)} />

</div>

</div>

);

}

 

It is important to note that the above code combines both useState() and useEffect() React hooks. The useState() is not different from the example highlighted above, which increases or decreases the count of sessions. The useEffect() hook gives the user an option to change a session. The initial session is Chemistry. You can change it to, let’s say, Biology by typing that name in the text box on the user interface.

When using this loop, you can set the conditions which need to be met for the hook to run. Excellent examples are;

If you want the hook to run once during the initial render, introduce this code;

useEffect(() => {

console.log(“This runs once on first render”);

}, []);

 

You can also ensure that the hook only changes if a particular value changes. In this case, this code will do the trick

useEffect(() => {

console.log(`${session} will rule the world!`);

}, [session]); // Only re-run the effect if the value of session changes

 

  1. useContext() React hook

Sometimes, an application may become deeply nested. Under such circumstances, you need a mechanism that allows particular data access to any application component. That’s where the useContext hook comes in, and it is important to acknowledge that it works alongside the React Context API. The duo provides a way to do so.

Since React only supports unidirectional data flow, so one can only pass data from a parent to a child. Developers do it manually using prop down until the data passes to the respective child component. The number of levels it will pass through to reach the child depends on how nested it is.

Extreme cases occur when dealing with an authenticated user, the theme of choice, or the preferred language, to mention a few. In such scenarios, one can only imagine how daunting it can be to pass these properties manually.

Fortunately, useContext() React hook and React Context API works jointly to make the data passage possible and easy.

The programmer uses React.createContext to facilitate the acceptance of the created context object

Expect the return of the current context to be as follows;

const value = useContext(SomeContext);

 

Let’s discuss an example;

Create a context that will use the useContext() hook

import React from “react”;

// some mock context values

const users = [

{

session: “Chemistry”,

nature: “Hard”,

},

{

session: “Biology”,

nature: “Easy”,

},

];

export const UserContext = React.createContext(users);

 

Due to the Provider wrapper of each context, child components will subscribe to any change in it. Additionally, it will pass down the new value to the context using a value prop. Consequently, updating the provider’s value prop leads to the child components re-rendering and displaying the new value while at it.

function Users() {

return (

<UserContext.Provider value={users}>

<UserProfile />

</UserContext.Provider>

);

}

 

Here is the complete code

import React, { useContext } from “react”;

import { UserContext } from “./App”;

 

export function UserProfile() {

const users = useContext(UserContext);

return (

<div>

{users.map((user) => (

<li>

This {session} session is {nature}!

</li>

))}

</div>

);

}

 

The results will be as follows

  • This Chemistry session is Hard
  • This Biology session is Easy

 

  1. useReducer() React

Last but not least is the useReducer React hook. It is quite similar to its useState counterpart. However, useReducer allows developers to introduce more complex state updates and logic, usually involving several sub-values.

Its working mechanism is no different, though, since it starts with creating state variables. Their changes will update the user interface.

Nevertheless, the useReducer accepts two arguments

  • Initial state: It’s the initial value of the state
  • Reducer function: It is a function that will accept the current and an action indicating how the state value will change

The syntax is as follows

useReducer(reducer, initialState);

The return of this hook is an array of a pair of values;

  • State: It is the current value of the state
  • Dispatch: It is also a function, but its role is to pass the action to the reducer to affect the state update

This return is as follows

const [state, dispatch] = useReducer(reducer, initialState);

 

This hook will use the following code to update the state values

unction reducer(state, action) {

switch (action.type) {

case “CASE_1”:

return {

updatedState,

};

case “CASE_2”:

return {

updatedState,

};

default:

return state;

}

}

 

The format of the dispatch function when dispatching an object is as follows

dispatch({ type: “ACTION_TYPE”, payload: optionalArguments });

The type describes the action, whereas the payload declares the arguments the dispatch function should pass to the reducer function.

 

Creating a Custom Hook

A developer can create a custom hook using the above React Hooks or even the other 6 not discussed above. It involves extracting component logic that one often uses from the user interface into JS functions. It is an appropriate approach when eliminating code redundancy since the logic will be reusable within various components.

Once you create that commonly used logic, there is no need to retype it whenever you need to use it in your application. You only need to import the function and pass an API path as the argument. It spares you from writing the same code again.

 

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *