Why typescript throw error at useState react

Asked
Active3 hr before
Viewed126 times

10 Answers

usestateerrorreacttypescript
90%

It seems like you are trying to use React Functional Components, as you are using the useState hook. ,In that case, you should not be creating a class and extending it from React.Component, as those are for defining class components. ,This is how you can define functional components using React and TypeScript.

This is how you can define functional components using React and TypeScript.

interface initialStateProps {
  eventInfo: {
    name: string; 
    location: string;
  }
}

const Dashboard: React.FC = () => {
  const [formValues, setFormValues] = useState<initialStateProps>({
    eventInfo: {
      name: '',
      location: ''
    }
  })

  return <div></div>

};
88%

Error and Exception handling is an easy task in React. You can also access the following URL for more updates:,Error Handling in Hooks is quite Simple. In this article, we are going to demonstrate how to handle errors in React Hooks. We need to create a mechanism where, if the error occurs while working with a component, user should receive an Error Component rather than throwing a run time error from the component. We will be using React Hooks in order to achieve the desired functionality.,In the code above, we are calling getter function of “hasError” and assigning it to a value “true”. Now, at any time, if the value of this variable is set to true, we need to render the “ErrorComponent”.

Pretag
 Pretag team - issue, fix, solve, resolve
72%

The return type of the first overload is the same, but here instead of S, S | undefined is used anywhere. If we don’t provide initial state it will store undefined initially. It means that undefined has to be included in the type of the piece of state stored by the hook.,The first overload doesn’t take any parameters - it’s used when you call useState without providing any initial state.,The first type of situation is when you don’t want to provide initial state to useState.

12
load more v
65%

Here, I'll show you how to declare the type of a state when you use the React Hook useState., We're a place where coders share, stay up-to-date and grow their careers. ,If you try to set a state with a value that does not match the type, you'll cause an error:

// ...
/**
* Returns a stateful value, and a function to update it.
*
* @version 16.8.0
* @see https://reactjs.org/docs/hooks-reference.html#usestate
*/
function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
      // convenience overload when first argument is ommitted
      /**
      * Returns a stateful value, and a function to update it.
      *
      * @version 16.8.0
      * @see https://reactjs.org/docs/hooks-reference.html#usestate
      */
      function useState<S=undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];
            // ...
load more v
75%

Concurrent React/React Suspense,Editor Tooling and Integration,A helper function that automatically types tuples can also be helpful if you write a lot of custom hooks:

Pretag
 Pretag team - issue, fix, solve, resolve
40%

To use that with TypeScript, we want to make sure that the return type from useMemo is the same as the return type from the callback:,For that, we create an ActionType type definition. We use union types to make sure that type can only be of reset, increment or decrement.,Making sure that the type property is set.

Pretag
 Pretag team - issue, fix, solve, resolve
22%

You are probably here because you got the following error message:,✅ Call them at the top level in the body of a custom Hook.,You can also try to debug this problem by adding some logs and restarting your development server:

function Counter() {
   // ✅ Good: top-level in a function component  const [count, setCount] = useState(0);  // ...
}

function useWindowWidth() {
   // ✅ Good: top-level in a custom Hook  const [width, setWidth] = useState(window.innerWidth);  // ...
}
load more v
60%

Now the hook’s return value is stored in result, a global variable. We can query it for our assertions.,This is the hook we will be testing:,Now, we can use it in our test. Instead of using act and render, we do the following:

Pretag
 Pretag team - issue, fix, solve, resolve
48%

From the get-go, we've got an error when calling setMode:,For us reading the code we know that setMode is a callable function, so the question is: why is the setMode type both a function and a string?,This expression is not callable. Because not all constituents of type 'string | React.Dispatch<SetStateAction<string>>' are callable. Because type 'string' has no call signatures.(2349)

.css-qnqv84{display:inline-block;width:2em;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;opacity:0.3;}1type DarkModeState = 'dark' | 'light'2type SetDarkModeState = React.Dispatch<React.SetStateAction<DarkModeState>>34function useDarkMode() {5  const preferDarkQuery = '(prefers-color-scheme: dark)'6  const [mode, setMode] = React.useState<DarkModeState>(() => {7    const lsVal = window.localStorage.getItem('colorMode')8    if (lsVal) {9      return lsVal === 'dark' ? 'dark' : 'light'10    } else {11      return window.matchMedia(preferDarkQuery).matches ? 'dark' : 'light'12    }13  })1415  React.useEffect(() => {16    const mediaQuery = window.matchMedia(preferDarkQuery)17    const handleChange = () => {18      setMode(mediaQuery.matches ? 'dark' : 'light')19    }20    mediaQuery.addEventListener('change', handleChange)21    return () => mediaQuery.removeEventListener('change', handleChange)22  }, [])2324  React.useEffect(() => {25    window.localStorage.setItem('colorMode', mode)26  }, [mode])2728  // we're doing it this way instead of as an effect so we only29  // set the localStorage value if they explicitly change the default30  return [mode, setMode] as const31}
load more v
23%

react-async - React component and hook for declarative promise resolution and data fetching.,Hooks are a new addition in React that lets you use state and other React features without writing a class. This website provides easy to understand code examples to help you learn how hooks work and inspire you to take advantage of them in your next project.,SWR - A React Hooks library for remote data fetching. Similar concept, but includes caching, automatic refetching, and many other nifty features.

Basically, what this hook does is that, it takes a parameter with value true or false and toggles that value to opposite. It's useful when we want to take some action into it's opposite action, for example: show and hide modal, show more/show less text, open/close side menu.

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 comopnent,
    // This function change the boolean value to it's opposite value
    const toggle = useCallback(() => setState(state => !state), []);
    
    return [state, toggle]
}
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: boolean = false): [boolean, any] => {
    // Initialize the state
    const [state, setState] = useState<boolean>(initialState);

    // Define and memorize toggler function in case we pass down the comopnent,
    // This function change the boolean value to it's opposite value
    const toggle = useCallback((): void => setState(state => !state), []);

    return [state, toggle]
}
load more v

Other "usestate-error" queries related to "Why typescript throw error at useState react"