CategoryTagArticle

admin

I'm a Full-stack developer

Tag

Linked List
Data Structure
Chat GPT
Design Pattern
Microservices
API
AWS CDK
ReactJS
AWS Lightsail
Flutter Mobile
Part 2: The hooks are used popularly in React
Published date: 18/06/2023

As a newbie React developer, does not understand when is use stateless (functional) components or stateful components. React hook is a new feature from v16.8, the developer does not worry about react lifecycle, and it is difficult to learn for newbies.


Previous article:

PART 1: REACT PROPS AND STATE



What is React Hook?


Hooks are the new feature introduced in the React 16.8 version and helped to isolate the stateful logic from the components. It allows you to use state and other React features without writing a class.


What rules need to be followed for hooks?


We need to follow two rules when using them:

  1. Call hooks only at the top level: you should not call hooks inside loops, conditions, or nested functions. Ensure hooks are called in the same order each time components render.
  2. Only call hooks from React functions: You shouldn’t call Hooks from regular JavaScript functions. Instead, you should call them from either function components or custom hooks.


Basic hooks


Hook state:

useState is React Hook that allows you to add state to a functional component. It returns an array with two values.


const [isLoading, setIsLoading] = useState(false);


Explain:

  • The initial value is false
  • isLoading is a current state in a component
  • The setIsLoading function can be used to update the current state, triggering a re-render of your component


Hook effect:

useEffect is a Hook that is used to manage side effects in functional components. A side-effect is any operation that impacts the component outside of its render, such as making an API call or setting up a timer. 


const [blogs, setBlogs] = useState([]);

useEffect(() => {
  fetch('https://dinhthanhcong.info/api/blogs')
    .then(res => res.json())
    .then(data => setBlogs(data));
}, []);

return (
  <ul>
    {blogs.map(blog => (
      <li key={blog.id}>{blog.name}</li>
    ))}
  </ul>
);


In this example, useEfffect is used to make an API call and then update the blog's state after the component is rendered. In this case, the empty array means that the effect will only run once when the component is mounted.


Hook memo:

useMemo is a hook that is used in the functional component of React that returns a memoized value. It is very useful in optimizing the performance of a React component by eliminating repeating heavy computations.


Let’s make an example to demonstrate:


const [num, setNum] = useState(0);

const increaseNum = () => {
  const newNum = num + 1;

  setNum(newNum);
}

return (
  <>
    <p>{num}</p>
    <p>Divisible By Five: {num % 5 === 0}</p>
    <button>Increase Num</button>
  </>
)


This means that every time the increaseNum() function is called, the Divisible By Five component is re-rendered unnecessarily, and the code becomes less efficient. We will fix this with the useMemo hook below.


const [num, setNum] = useState(0);

const increaseNum = () => {
  setNum(num + 1); 
}

const divisibleByFiveHook = useMemo(() => {
  return num % 5 === 0;
}, [num])

return (
  <>
    <p>{num}</p>
    <p>Divisible By Five: {divisibleByFiveHook}</p>
    <button>Increase Num</button>
  </>
)


In the code above, we set the output of the divisibleByFiveHook() function into a constant memoHook.

This filters the function through the useMemo hook to only check if the specified variable (num in this case) has been changed; only then will this function be rendered.


Hook callback:

The useCallback and useMemo Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function.


Hook ref:

useRef() only returns one item, and it returns an Object called the current. It can be applied to directly access a DOM element. When updated, it can store mutable values without requiring a re-render.


You would need to access DOM elements, for example, to focus on the input field when the component mounts.

const inputRef = useRef();

useEffect(() => {
  inputRef.current.focus();
}, []);

return (
  <input 
    ref={inputRef} 
    type="text" 
  />
);


Summary


Besides basic hooks, React has some other hooks (useContext, useDebugValue, ...). You can follow this link to read more.


Thank you for reading!


Next article:
PART 3: REACT FRAGMENTS


References:

https://blog.logrocket.com/guide-usestate-react/#:~:text=useState%20is%20React%20Hook%20that,the%20setter%20function%20is%20called

https://www.educative.io/answers/what-is-the-usememo-hook-in-react

Recommend

Part 3: React Fragments
admin18/06/2023

Part 3: React Fragments
In this part, I will show you about good benefits when using fragments in React.
How to secure your API gateway
admin17/04/2024

How to secure your API gateway
In this blog, I will cover the 6 methods that technology leaders need to incorporate to secure and protect APIs.
Part 4: Creating Static Home Page on Ghost CMS
admin17/06/2023

Part 4: Creating Static Home Page on Ghost CMS
I believe that many of you are asking the question: How to fix the home page of Ghost CMS as desired? and are struggling to find many different sources of documentation.
Newest

Create Cognito User Pool with AWS CDK
admin09/06/2023

Create Cognito User Pool with AWS CDK
In the previous post, I showed you how to create a simple S3 bucket. Next, in this article, I will guide you to create a Cognito User Pool.
TypeScript Design Pattern - Builder
admin07/08/2023

TypeScript Design Pattern - Builder
TypeScript Design Pattern - Builder
How to create scroll animations with Next.js App
admin08/04/2024

How to create scroll animations with Next.js App
A Beginner's Guide to Using AOS Library with Next.js application
Đinh Thành Công Blog

My website, where I write blogs on a variety of topics and where I have some experiments with new technologies.

hotlinelinkedinskypezalofacebook
DMCA.com Protection Status
Feedback
Name
Phone number
Email
Content
Download app
hotline

copyright © 2023 - AGAPIFA

Privacy
Term
About