Home > other >  useState initial state is undefined (TypeError: setNav is not a function) [closed]
useState initial state is undefined (TypeError: setNav is not a function) [closed]

Time:09-28

const {nav, setNav} = useState(true);
const changeState = () => {
    setNav(false)
};

useEffect(() => {
    changeState();
}, [nav]);

In this code snippet, I am setting the initial state as "true" and changing it to "false". No matter what state I set or change it throws a TypeScript error (undefined):

error

CodePudding user response:

useState returns an array with two elements, not an object:

const [nav, setNav] = useState(true);
//    ^           ^

React couldn't possibly know how you want to name your state, so it can't return an object with these properties.

CodePudding user response:

Just replace const {nav, setNav} = useState(true); by:

const [nav, setNav] = useState(true);

As useState returns an array

  • Related