Search code examples
javascriptreactjsreact-hooksuse-statereact-custom-hooks

Question regarding useToggle(custom hook) vs useState hook in react


Below code is a custom Hook called useToggle from a website, it's defined as a custom hook that can be useful when showing/hiding a modal but I don't understand why to go through such code for such a simple feature. Isn't it better to just use useState()

useToggle custom hook

import { useCallback, useState } from 'react';
// Usage
function App() {
    // Call the hook which returns, current value and the toggler function
    const [isTextChanged, setIsTextChanged] = useToggle();
    
    return (
        <button onClick={setIsTextChanged}>{isTextChanged ? 'Toggled' : 'Click to Toggle'}</button>
    );
}
// Hook
// Parameter is the boolean, with default "false" value
const useToggle = (initialState = false) => {
    // Initialize the state
    const [state, setState] = useState(initialState);
    
    // Define and memorize toggler function in case we pass down the component,
    // This function change the boolean value to it's opposite value
    const toggle = useCallback(() => setState(state => !state), []);
    
    return [state, toggle]
}

Just using normal useState()

const [shouldDisplayModal, setShouldDisplayModal] = useState(false);

<>
    {shouldDisplayModal && (
      <Modal>
        <ModalContent
          modalText={messageContent}
          primaryButtonText={buttonText}
          secondaryButtonText={NO_MESSAGE}
          modalIconState={modalIconState}
          handleClick={toggleSaveModal}
        />
      </Modal>
    )}
        <Button handleClick={toggleSaveModal} mainButton={false}>
          Save
        </Button>
        <Button handleClick={togglePublishModal} mainButton={true}>
          Publish
        </Button>

  </>

Solution

  • The main purpose of introducing your own/custom hook is to tackle a scenario where none of the built-in hooks serve you properly. Or in some cases to achieve code reusability.

    In the example you shared, the main reason might be to have a reusable piece of code for toggling the state of all Modals. Imagine there are multiple Modals across the app, by using a custom hook you won't be needed to write getter and setter functions again and again.

    The example you shared is a simpler one, you can imagine having a hook that performs much more functionality than that, like a hook for API calls, etc.

    So, it all comes down to your use case.