Should Custom React Hooks Cause Re-Renders of Dependent Components?

I just created a custom hook that uses useState and useEffect internally.

When I import that hook into another React function component, call it ComponentA, ComponentA re-renders whenever the state in the custom hook changes.

Is it correct that ComponentA should re-render, when hooks that it uses returns new values?

See comments in the code, for additional question clarifications.

Code:

const ComponentA = props => {
  const myValue = useMyValue();

  // COMMENTS:
  // Whenever myValue returns a new value, ComponentA re-renders
  // This in turn will cause the useMyValue() function to run.
  // Seems unnatural with such a circular effect.
  // Is my suspicion unfounded? Is this how it should work?
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

A custom can be treated as a function simply which is executed from within the functional component and effectively the hooks that are present in the custom hook are transferred on to the component. So any change that would normally cause the component to re-render if the code within the custom hook was directly written within functional component will cause a re-render even if the hook is a custom hook.

Method 2

Hooks are simple functions which can use other hooks and a function cannot return a value unless it is called,
here if we are maintaining useState or useEffect inside custom hooks then on rendering the component first call custom hook (here useMyValue will be called), with the instance of componentA, which in turn call useState or useEffect hooks inside of it, with the same componentA instance, and return the intialized value to componentA.

const useMyValue = () => {
  const [count, setCount] = useState(0);
  // ...do something
  return [count, setCount];
};

const ComponentA = (props) => {
  const [value, setValue] = useMyValue();
};

now if are updating the value in componentA and we are calling setValue which has the reference of setCount from custom hooks then count got updated but useState will also update/ re-render the component for which it holds the instance, here componentA, and on re-rendering componentA will again call useMyValue hook which in turn call useState again and receive the updated value for count and finally return its updated value to the componentA.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x