React Hook case collection

React Hook is essentially a function whose name is   “use”   At the beginning, other functions can be called inside the function   Hook, the result will generally have a return value. The purpose of using hook is to extract the common logic of multiple components. This paper uses six cases to familiarize you with the use of React Hook.

First, let's take a look at the first case, a simple hook function, which does nothing but familiarize you with the definition of hook:

import { useState } from 'react'

const useMyHook = (initValue) => {
  const [value, setValue] = useState(initValue || '')
  return value
}

function App() {
  const myHookValue = useMyHook('myHook')
  return <div className="app">{myHookValue}</div>
}

From the above code, we can see that I have customized a custom hook named useMyHook, which has no function, but is only used to return a custom value.

In the second case, let's upgrade the above case and add an input to make you more aware of the custom hook. We now need to have an input box and use a custom hook to transfer values and modify function values:

import { useState } from 'react'

const useMyHook = (initValue) => {
  const [value, setValue] = useState(initValue || '')
  const onChange = (e) => {
    setValue(e.target.value)
  }
  return { value, onChange }
}

function App() {
  const myHookValue = useMyHook('myHook')
  return (
    <div className="app">
      <p>value:{myHookValue.value}</p>
      <input value={myHookValue.value} onChange={myHookValue.onChange} />
    </div>
  )
}

In the above code, we build a case where we can change the data in real time by entering the content in the input box. It is implemented through a custom hook useMyHook. Here, we return a value in the custom hook to display the current value. An onChange function to modify the current value. When we use it, the p tag shows the current value, the input change function uses onChange in customization, and the value in myHookValue is displayed.

The third case: suppose there is a function in our component that can retrieve the width of the window. We want to know when the user resizes the screen. Instead of using hook, we can write:

const LayoutComponent = () => {
  const [onSmallScreen, setOnSmallScreen] = useState(false);

  useEffect(() => {
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);
  }, []);

  let checkScreenSize = () => {
    setOnSmallScreen(window.innerWidth < 768);
  };

  return (
    <div className={`${onSmallScreen ? "small" : "large"}`}>
      <h1>Hello World!</h1>
    </div>
  );
};

We have a component with onSmallScreen state, which knows whether we are in a window with a width of less than 768 pixels. To know this, we used useeffectshook. In this hook, we first call the checkScreenSize function, which updates the onSmallScreen state variable. Finally, we bind the checkScreenSize function to the resizing event listener to update the status if necessary when a resizing event occurs.

Next, we extract the code to obtain the page width and construct a hook:

import { useState, useEffect } from "react";

const useWindowsWidth = () => {
  const [isScreenSmall, setIsScreenSmall] = useState(false);

  let checkScreenSize = () => {
    setIsScreenSmall(window.innerWidth < 600);
  };
  useEffect(() => {
    checkScreenSize();
    window.addEventListener("resize", checkScreenSize);

    return () => window.removeEventListener("resize", checkScreenSize);
  }, []);

  return isScreenSmall;
};

export default useWindowsWidth;

Then we call it where we need to get the page width:

import React from 'react'
import useWindowWidth from './useWindowWidth.js'

const MyComponent = () => {
  const onSmallScreen = useWindowWidth();

  return (
    // Return some elements
  )
}

In the fourth case, we can extract the storage of localstorage:

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

export default function useLocalstoagehook(key) {

  const [name, setName] = useState(() => {
    const name = JSON.parse(localStorage.getItem(key))
    return name
  })

  useEffect(() => {
    // localStorage.setItem('name', name)
    localStorage.setItem(key, JSON.stringify(name))
  }, [name])
   
  return [name,setName]

}

Call where needed:

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

import useLocalstoagehook from '../hook/localstoagehook'

export default function CustomLocalStorage() {
  
  const [name,setName]= useLocalstoagehook('name')

  return (
    <div>
      {name}
      <button onClick={e => setName('lsh')}>set up</button>
    </div>
  )
}

The fifth case, for example, assumes that you have components that display a list of comments for an article. We can imagine a few lines:

const ArticleWithComments = (articleId) => {
  const [comments, setComments] = useState([])
  const [error, setError] = useState(null)

  let handleCommentsSuccessFetch = (articleComments) => setComments(articleComments)

  let handleError = error => setError(error)

  useEffect(() => {
    fetchComments(articleId, handleCommentsSuccessFetch, handleError)
  }, [])

  return (
    // Do something in the DOM
  )
}

const BlogPostWithComments = (blogPostId) => {
  const [comments, setComments] = useState([])
  const [error, setError] = useState(null)

  let handleCommentsSuccessFetch = (blogPostComments) => setComments(blogPostComments)

  let handleError = error => setError(error)

  useEffect(() => {
    fetchComments(blogPostId, handleCommentsSuccessFetch, handleError)
  }, [])

  return (
    // Do something in the DOM
  )
}

In this example, we have two components. Both of them get a list of comments based on their ID (post ID or blog post ID). In useEffect hook, we have an API call that retrieves these comments through two functions. One sets the status to comment in case of success, and the second sets the status to error in case of error. However, the functionality is duplicated between the two components. Fortunately, we can extract this feature in the custom hook:

const useCommentsRetriever = (entityId) => {
  const [comments, setComments] = useState([]);
  const [error, setError] = useState(null);

  let handleCommentsSuccessFetch = (comments) => setComments(comments);

  let handleError = (error) => setError(error);

  useEffect(() => {
    fetchComments(entityId, handleCommentsSuccessFetch, handleError);
  }, []);

  return [comments, error];
};

Here, we have hook usecomments retriever. It takes an entityId as a parameter. This will be the ID of our post or the ID of our blog post. Then, it is similar to the content in the component. The difference is that this custom hook needs to return something. I choose to return an array here. The first element is a comment and the second element is an error. It will be used in this way:

//Import the custom hook
import useCommentsRetriever from './useCommentsRetriever.js'

const ArticleWithComments = (articleId) => {

  const [comments, error] = useCommentsRetriever(articleId)

  return (
    // Do something in the DOM
  )
}

const BlogPostWithComments = (blogPostId) => {

  const [comments, error] = useCommentsRetriever(blogPostId)

  return (
    // Do something in the DOM
  )
}

See how much code we need to write? The useCommentsRetriever takes an id as a parameter. This [comments, error] is what we call array deconstruction. hookuseCommentsRetriever returns an array. We assign the first item of the array to the variable name annotation and the second item of the array to the variable name error.

The above is a collection of react hook cases. I hope it will help you.

Posted on Tue, 07 Dec 2021 00:52:52 -0500 by danielle