7

In my React app, I have a custom defined hook that holds a useState value internally, but the custom hook itself does not return any values.

If the value of its internal useState changes would this cause the component that calls this custom hook to re-render?

2 Answers2

19

Yes it re-renders the component. The custom hooks helps to reuse stateful logic in different components, but in the end, when you use a custom hooks all states and effects inside of it are part of the component where you called the custom hook. So yes, the change of state inside the custom hooks re-renders the component where you used your custom hook, even when this does not return anything.

Angel Hdz
  • 715
  • 1
  • 3
  • 7
-1

No, it does not re-render the component.

From the documentation (https://reactjs.org/docs/hooks-custom.html):

Do two components using the same Hook share state? No. Custom Hooks are a mechanism to reuse stateful logic (such as setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.

Example Hook:

export function useExample () {
    const [saveCount,setSaveCount] = useState(0);
    
    console.log('Internal saveCount value',saveCount);
    
    const save=()=>{
        return fetch(blah, blah, blah).then((result)=>{
            setSaveCount((prev)=>{
                return prev+1;
            });
            return result;
        });
    }

    return {
        saveCount:saveCount,
        save:save
    }
}

Example Component that consumes it:

export function MyComponent (props) {
    const { saveCount, save } = useExample();
    
    console.log('External saveCount value',saveCount);
    
    const onClick=()=>{
        save();
    }
    
    useEffect(()=>{
        console.log('Effect saveCount value',saveCount);
    },[saveCount]);
    
    return (
        <Button onClick={onClick}>Blah, blah, blah</Button>
    )
}

If you click the button, the "save" function will execute, and you'll see the "Internal saveCount value" message with the incremented value, but you will not see any of the change messages in the component. The hook's state belongs to it, and it alone.

Alan Schmidt
  • 113
  • 7
  • I don't know why this is downvoted when it is in fact the correct answer - hook state is not shared between components – NbonD Jan 17 '23 at 11:12
  • 1
    @NbonD the question never asked about multiple components using same hook scenario. It's a wrong answer. The example is even misleading with the referenced document. Whether you return the value of the hook's state or not, it will cause the Component to re/render. – duduwe Jan 17 '23 at 20:50
  • Actually, you CAN see the change messages in the component. Whenever the hook's state changes it is reflected in the MyComponent (via a re-render). – Kostas Minaidis Jan 18 '23 at 00:32