简体   繁体   中英

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?
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM