Home > other >  Why is hook not reusable?
Why is hook not reusable?

Time:07-29

I created a custom hook as follows:

import { useState } from 'react';

export const useMyHook = () => {
  const [isVisible, setIsVisible] = useState(false);

  function toggle() {
    setIsVisible(!isVisible);
  }

  return { isVisible, toggle,}
};

I am only able to use it once (see comment below). When I call the hook again with different const, I get the error:

Property 'isVisible2' does not exist on type '{ isVisible: boolean; toggle: () => void; }'. TS2339

import React from 'react';
import useModal from './useMyHook';

export const App = () => {

  const {isVisible, toggle} = useMyHook();    // Example of using once
  const {isVisible2, toggle2} = useMyHook();  // am not able to use it here
  const {isVisible3, toggle3} = useMyHook();  // am not able to use it here

  return (<div> Hello world! </div>);
};

I am incorrectly assuming that creating a new const var allows the reuse of the hook. What am I doing incorrectly?

CodePudding user response:

Right now, you're returning an object with two properties: isVisible and toggle.

Either destructure into differently-named variables (verbose; not great):

const {isVisible: isVisible2, toggle: toggle2} = useMyHook();

Or return an array from the hook instead:

return [isVisible, toggle];

and

const [isVisible2, toggle2] = useMyHook();

CodePudding user response:

Because in your custom hook, you return an object with 2 properties: isVisible and toggle. But you destructured it into isVisible2 and toggle2. You can see, there are no isVisible2 and toggle2 in your return. So, if you want to use this hook again try to assign it to a new variable name like this:

const {isVisible: isVisible2, toggle: toggle2} = useMyHook();
  • Related