G
G
gsaw2022-01-04 13:25:59
React
gsaw, 2022-01-04 13:25:59

How does it work with a custom hook?

Please help me understand how it works?

https://ru.reactjs.org/docs/hooks-custom.html

The link above explains how to write custom hooks and the following hook is given as an example.

import { useState, useEffect } from 'react';

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
    };
  });

  return isOnline;
}


And this is how it is used

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);


It's completely unclear to me how the new value will get into the FriendStatus component.

As I understand all this,
1. the FriendStatus function is called to draw the component.
2. Which, in turn, calls the useFriendStatus function
3. in the useFriendStatus function, in turn, useState is called
4. A function is created using useEffect, which then calls setIsOnline
5. The isOnline value is returned

As I understand it, at some point in time, a response will come from the server and the setIsOnline method will be called, and somewhere in the bowels of useState isOnline will change its value.

As far as I understand everything, now the react needs to call the FriendStatus function again, so that it in turn calls useFriendStatus, which in turn calls useState and returns the new isOnline value.

A question that I don't understand. From where does react know that it is necessary to redraw FriendStatus, that is, pull the FriendStatus function? How does he know that this component depends on useFriendStatus, which in turn depends on Or react, if isOnline changes, stupidly redraws all components, calls all component functions? Thanks const [isOnline, setIsOnline] = useState(null);


Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gsaw, 2022-01-04
@gsaw

Sorry, I just didn't see it right away. The answer was found here
https://ru.reactjs.org/docs/hooks-faq.html#how-doe...
react really binds hooks to components by keeping track of the order of useState calls. That is, knowing which component is being drawn at the moment, you can find out which hooks correspond to it. And next time, redraw only what you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question