DEV Community

Eyitayo Itunu Babatope
Eyitayo Itunu Babatope

Posted on

React Hooks Made Easy

Introduction:

React Hooks allow functional components to use React features such as state and life cycle methods. Functional components use hooks to maintain state, fetch data from an external source, cache results of an expensive calculation, and receive data from distant parent components without passing it as props. Knowing which React hooks to use can be tricky. In two articles series, we will look at each of the React Hooks and demonstrate their usage with code examples.

These two articles series are for React developers who wish to better understand React hooks. The article assumes the reader has basic knowledge of React, functional components, lifecycle methods, and how to include React library in a project.

In this article, the reader will learn about

  • Rules for hooks
  • How to use hooks
  • Categories of Built in hooks
  • Usage of hooks

Rules for Hooks

  • Hooks are call within a functional component.
  • Hooks are call at the top level of a component.
  • It cannot be conditional
  • Hooks begin with the keyword use.

How to use Hooks in an application

To use hooks in an application, we import the hooks using the keyword import.

import {useState} from "react"

Enter fullscreen mode Exit fullscreen mode

In the above example, we imported the useState from React. We can import more than one hooks. See the example below.

import {useState, useEffect} from "react"

Enter fullscreen mode Exit fullscreen mode

React comes with built-in hooks. Also, we can customize hooks to meet specific requirements.

React Built-Hooks are categorize into the following groups:
1)State Hooks
2) Effect Hooks
3) Context Hooks
4) Performance Hooks
5) Other Hooks

React State Hooks

State in react is a built-in react object that stores data or value of a property. State let component remember user input between re-render. When the value of a property changes, react re-renders the component.
useState and useReducer are two hooks that manage the state in React.

React useState

useState is a react hook that updates or sets the value of a property directly. The useState returns an array of two values. The current state and a function that sets or updates the current state.

1 import React,{useState} from 'react';
2 function MyText(){
3 const [myText, setText]=useState('first Text');
4 const handleSubmit=(event)=>{
5    event.preventDefault();
6    const textForm=document.forms['textForm']['mytext'].value
7   setText(textForm)
8 }
9 return(
10    <>
11    <div>{myText}</div>
12    <form name="textForm" onSubmit={handleSubmit}>
13        <textarea name="mytext"  cols={20} rows={10} />
14        <button type="submit">Click Me</button>
15    </form>
16    </>


17 )
18 }
19 export default MyText;
Enter fullscreen mode Exit fullscreen mode

Line 1: We imported useState.
Line 2: We created a react functional component called MyDetails.
Line 3: We initialized useState with a string and deconstructed the array returned by useState with variable text and function setText.
Line 4: We declared a function to handle the form submission.
Line 5: We called the event.preventDefault function to prevent default form propagation.
Line 6: We assigned the value of the textarea element to the variable textForm.
Line 7: Called setText to set the value of myText.
Line 9: Return JSX of MyText component.

React useState hook can be initialized with an empty string, an object, or an array. See the code example below.



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

2 function MyDetails(){
3 const [myDetails, setMyDetails]=useState({'firstname':"",'lastname':' ','age':0});
4 const handleSubmit=(event)=>{
5    event.preventDefault();
6    const fname=document.forms['detailsForm']['fname'].value
7    const lname=document.forms['detailsForm']['lname'].value
8    const age=document.forms['detailsForm']['age'].value
9    setMyDetails({firstname:fname,
10    lastname:lname,
11    age: age    })
12 }
13 return(
14    <>

15    <form name="detailsForm" onSubmit={handleSubmit}>
16       <label>Firstname</label>
17        <input type='text' name='fname' />
18        <label>Lastname</label>
19        <input type='text' name='lname' />
20       <label>Age</label>
21        <input type='number' name='age' min='1' max='100'/>

22        <button type="submit">Click Me</button>
23    </form>
24    <ul>
25        {Object.entries(myDetails).map(([index,element]) => {
26          return (<li key={element}>{index}:{element}</li>)
27        })
28        }
29    </ul>
30    </>


31 )
32 }
33 export default MyDetails;
Enter fullscreen mode Exit fullscreen mode

Line 3: We initialized useState with an object with firstname, lastname, and age as properties.

Line 4: We declared the handleSubmit function with an event argument.
Lines 6,7,8: We assigned the values of the input fields to variables.
Line 8: We called the setMyDetails to set the value of the properties of MyDetails.
Line 13: It rendered JSX of the MyDetails component.
Line 25: We called the Object.entries function to transform myDetails into an array of key and value pairs and iterated through the returned array with the array.map function.

useReducer

useReducer sets or updates state but the logic to update the state is in another function called reducer.
useReducer takes three arguments: the reducer function, the initial argument, and an init function(optional). The init function returns the initial state. If it is not specified, it defaults to the initial argument. The useReducer returns an array of two values: the current state and a dispatch function that lets you update the current state to a new value.

1 import React,{useReducer} from 'react';
2 function reducer(jobDescription,action){

3   switch(action.type){
4.      case "janitor":
      5 return{category: action.type}
6       case "manager":
        7 return{category: action.type}
8       case "secretary":
        9 return{category: action.type}
10       default:
          11 return " ";
    }

}
12 const initialArg={category:""}
13 function Employee(){
14 const [jobDescription, dispatch]= useReducer(reducer,initialArg);

15 return(
    <>
16   <select name='jobs' onChange={(event)=>{
         dispatch({type:event.target.value})
    }}>
17        <option value=" "> </option>
18        <option value="janitor">Janitor</option>
19       <option value="secretary">Secretary</option>
20        <option value="manager">Manager</option>
    </select>
21   <div>Your job description is {jobDescription.category}</div>
    </>


)
}
22 export default Employee;
Enter fullscreen mode Exit fullscreen mode

Line 2: We declared a reducer function with two arguments; jobDescription(state) and action
Line 3-11: We passed action.type through a switch block, each case set the category and returned the updated category.
Line 12: We declared a variable initial argument and initialized it with an object that has a category field with an empty value.
Line 13: We declared an Employee component.
Line 14: We called a useReducer hook with two arguments; reducer function and intialArg. The useReducer returned an array of two values which we deconstructed into variable jobDescription(state) and a dispatch function.
Line 16: We used the HTML select tag to create four options field, with an onChange event listener. Whenever there is a change in the selected value, the dispatch function will be called inside the event listener.
Line 17-20: The different option.
Line 21: We rendered the current jobDescription(state).

Conclusion:

In part 1 of react hooks, we defined hooks, enumerated the rules for hooks, and mentioned various types of hooks. We demonstrated how to use useState and useReducer hooks with code examples. In part two of react hooks, we will discuss other react hooks.

Top comments (0)