React and React Hooks

958 VIEWS

·

React is a JavaScript library. You can use it to build user interfaces for both websites and web applications. It is based on reusable UI components. React hooks are features that allow you make use of the react lifecycle without writing a class. In this article I will focus on react hooks and how you can apply them.

React and React Hooks

React is a flexible JavaScript library that helps build interactive user interfaces. These user interfaces are built based on components which can be reusable. JSX is a syntax extension to JavaScript. It produces react elements placed in react components. You can use React library to build web applications and websites.

What are React Hooks?

It is important to note that React hooks are different from web hooks. Web hooks are user-defined HTTP callbacks, which is a method that allows web apps to communicate as soon as a particular event takes place. React hooks are new features in React version 16.8 used in functional-based components. Before react hooks, you could only use states in class-based components. The introduction of these new features made it possible to use state in functional components. The different react hooks we will look at are the useState hook, useEffect hook, useContext hook, useReducer, useRef, useMemo, useCallbacks and custom hooks.

Using React Hooks

The introduction of hook allows us to share stateful logic in a better way without changing the component hierarchy. Without hooks, there is no particular way to reuse stateful component logic. Hooks let us split one component into smaller functions based on the related pieces rather than forcing a split through the life cycle method. It lets us organize the logic into reusable isolated units, this allows us to avoid trivial bugs and inconsistencies.

Let’s dive right into react hooks and how you can use them.

The useState Hook 

This hook allows you to use state variables in functional components. To use the useState hook, we first need to import it into the component, as shown below.

import { useState } from 'react'

The useState hook is a function so after importing it into our component we call it, and assign an initial value:

useState(0);

The useState hook returns two values which include a current state and a function that updates the state. In the example below, count is the current state, while setCount updates the state:

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

Now let’s dive into creating a simple counter in our component to demonstrate how you can use useState hooks:

import { useState } from 'react'
 
const counter = () => {
    const initial = 0;
    const [count, setCount] = useState(initial);
   
    const increment =() => {
        for(let i= 0; i<2; i++){
            setCount(previous => previous +1)
        }
    }
    
    return (
      <div>
        <button onClick = {()=> setCount(count + 1)}> add</button>
        <button onClick = {()=> setCount(count - 1)}> sub</button>
        <button onClick = {()=> setCount(initial)}> reset</button>
        <button onClick = {increment}> increment</button>
        
 
        <h1>{count}</h1>
      </div>
    )
}
export default counter

The useState hook takes in different values such as strings, numbers, Booleans, arrays and objects.

This example shows how the useState handles objects:

function Learn() {
  const [person, setPerson] = useState({
    name: "Freda",
    age: 20,
    favouriteColor: "blue"
  });
 
  return (
    <>
      <h1>I have a friend named {person.name}</h1>
      <p>
      {person.name} favorite color is {person.favouriteColor} .
      </p>
    </>
  )
}
The useEffect Hooks

Just as the name implies, it allows you to add side effects to the components. The side effect includes fetching data, using timers  and updating the DOM. To use the useEffect, just as we imported the useState we have to import it first into our component:

import { useEffect} from 'react'

The useEffect accepts two arguments: the function that carries the side effect logic and the dependencies. Whenever there is a change in the dependencies between renderings, the useEffect executes the callback. The dependencies are mostly arrays and are optional.

useEffect(Function, dependencies)

Here is an example showing the useEffect hook:

import { useState, useEffect} from 'react'
 
function Count() {
  const [number, setNumber] = useState(0);
 
  useEffect(() => {
    setTimeout(() => {
      setNumber((number) => number + 1);
    }, 2000);
  }, []); 
 
  return <p>this is {number} times</p>;
}
The useContext Hook

The useContext hook makes data available to all nested components without passing in props. You can use it to create data that can automatically pass throughout the component hierarchy, instead of manually passing props down to each level. Here is an example:

import { useState, createContext, useContext } from "react";
const personContext = createContext();
function firstComponent() {
  const [person, setPerson] = useState("John Doe");
 
  return (
    <personContext.Provider value={person}>
      <h1>{`Hello ${person}!`}</h1>
      <SecondComponent user={person} />
    </personContext.Provider>
  );
}
 
function SecondComponent() {
  return (
    <>
      <h1>SecondComponent</h1>
      <ThirdComponent />
    </>
  );
}
function ThirdComponent() {
  const user = useContext(PersonContext);
 
  return (
    <div>
      <h1>ThirdComponent</h1>
      <h2>{`Hi ${person} `}</h2>
    </div>
  )
}

Then the content provider wrapped all the components, giving all the nested components access to the data.

The useReducer Hook

This hook has a similar function to the useState hook. It helps us  manage complex state logic in react applications. It is used to store and update states and it accepts two parameters. A reducer and  the initial state:

useReducer(reducer, initialState)

It returns an array and a dispatch function. The array holds the current state value while action is passed in the dispatch function.

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

The useReducer hook is demonstrated in the example below:

import { useReducer} from 'react'
 
 
const initialState = {count: 0};
 
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return {count: state.count + 1};
    case 'decrement':
      return {count: state.count - 1};
    default:
      throw new Error();
  }
}
 
function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
    </>
  );
}
The useRef Hook

This is a react hook that accepts an argument as the initial value and returns a reference which has a property known as current. You can use it to directly access a DOM element, to keep track of previous state values, and to store mutable values that do not cause a re-render when updated. Here is an example on how to use useRef:

import  { useState, useEffect, useRef } from "react";
 
export default function Learn() {
  const [name, setName] = useState('');
  const count = useRef(1)
 
  useEffect(()=>{
    count.current = count.current + 1
  })
  
  
  return (
    <>
    <input value = {name} onChange = {e => setName(e.target.value)}/>
    <h1>{`The component has been re-rendered ${count.current} times`}</h1>
    <p>{name}</p>
 
    </>
  )
  }
Custom Hooks

Custom hooks are created whenever we want to share logic between other javascript functions. One solid purpose of custom hooks is for code reusability. With custom hooks we can write a code and share it across multiple components that use the same stateful logic.

useMemo

The react useMemo hook helps to prevent multiple re-rendering. You can use it to keep expensive functions from needlessly running and make the functions run only when necessary. It returns a memorized value. Here is an example:

import { useState, useMemo } from 'react'
 
export default function Learn()  {
  const [numb, setNumb] = useState(0)
  const [dark, setDark]= useState(false)
  const doubleNum = useMemo(()=>{
    return slowDown(numb)
  }, [numb])
 
  const themeStyles = {
    backgroundColor: dark? 'black':'white',
    color:dark? 'white': 'black'
  }
  return (
    <div>
      <input type = 'number' value = {numb} onChange = {e => setNumb(parseInt
        (e.target.value))}/>
        <button onClick = {()=> setDark(previousDark => !previousDark)}>change themeStyles</button>
        <div style = {themeStyles}>{doubleNum}</div>
    </div>
  )
}
 
function slowDown(num){
  for(let i = 0; i<=1000000000000; i++){
    return num*2
  }
}
The useCallbacks

The useCallbacks is similar to the useMemo, but it returns a memoized function. It prevents re-creation of a specific function as the component re-renders. It also prevents unnecessary renders.

Conclusion

React is a javascript library that has given us an easy way of building websites and web apps by providing us with reusable components and hooks to make the process of web development easier.

If you want to learn more about what you can do with React hooks, take a look at this article: “Creating Form Validations with React Hooks


Faith Njah is a front-end developer, with experience in building dynamic websites using web technologies like HTML, CSS, JavaScript, and A-frame VR. She is also passionate about learning.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published.

Menu
Skip to toolbar