What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState

type Mode = 'confirm' | 'deny'  
type Option = Number | null

const [mode, setMode] = React.useState('confirm')
const [option, setOption] = React.useState(100)

In the current code, mode is recognized as string, but I want it to be recognized as Mode. The same issue applies to Option.

What is the best way to add type notation to React.useState?

Answer №1

React.useState utilises a generic approach, allowing for the addition of type notation as shown below:

const [mode, setMode] = React.useState<Mode>('confirm')
const [option, setOption] = React.useState<Option>(100)

It is worth noting the type definition of React.useState:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include the "onChange" function in a component that does not natively support this prop?

After finding a useful code snippet on this page to switch languages, I attempted to enhance it by incorporating material UI components for better styling. However, whenever I change the language, it redirects me back to the home page because the MenuList ...

Is it feasible to create a personalized shopping cart using React with Snipcart?

Currently, I am in the process of developing a new website using Next and have integrated Snipcart. The Snipcart UI incorporates Vue.js along with embedded images and an external CSS file, which unfortunately contribute to a significant increase in the pag ...

Creating a line of functions pool in Javascript with a delay feature

Recently, I created a code snippet that simulates a function line. It involves calling functions such as fn1, delay, fn2, delay, and so on. The idea is to call a function, remove it from the line, have a short sleep, and repeat. However, I've encount ...

Convert price to Indonesian Rupiah currency format with the help of Vue.js

Can someone help me convert the price format from IDR 50,000.00 to IDR 50.000 using JavaScript and Vue? I found a script on this website, but I am having trouble understanding how it works. The script looks like this: replace(/(\d)(?=(\d{3})+(?: ...

Antd CSS application is experiencing a delay

Upon refreshing the page on Next.js with Antd CSS, I am experiencing a delay in applying the styles. The content appears misaligned right after the reload. Is there a way to fix this issue? I suspect it may be related to SSR, but unfortunately, I have not ...

Tips for incorporating attributes into a customized Material-UI props component using TypeScript in React

I'm interested in using material-ui with react and typescript. I want to pass properties to the components, but I'm having trouble figuring out how to do it. Currently, I'm working with the react-typescript example from the material-UI repos ...

Adjust the outline hue of MUI SvgIcon by utilizing a personalized SVG

When working with custom SVGs, I have found that I can easily change the fill color using SvgIcon. import { ReactComponent as MyIcon } from '../my_custom_logo.svg'; <SvgIcon component={MyIcon} inheritViewBox color="primary" /> Ho ...

Guide to iterating through an Observable<Object[]> to generate an array of objects

Google Firestore collection named users is structured as follows : { "contactNumber":"0123456789", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e2e7e0e6ece7edc8efe5e9e1e4a6ebe ...

Using JavaScript to locate a child element within its parent

What is the most effective approach to locate a child element (using class or ID) of a specific parent element using only pure JavaScript without relying on jQuery or other frameworks? In this scenario, I am interested in finding child1 or child2 within p ...

Is it possible to close the navigation menu by clicking on a link or outside of the navigation area?

Hey everyone, I've recently dived into the world of web design and encountered my first hurdle. I need your expertise to help me solve this problem. How can I modify my JavaScript to close the NAV element by clicking on one of the links or outside t ...

What is the best way to access the next-auth session using getStaticPaths and getStaticProps in dynamic routing scenarios?

I am currently working on implementing dynamic routing in a NextJS application. I need to retrieve the token from next-auth in order to make axios requests to an API and fetch data from getReport and getReports (located in /reports.js). However, I am facin ...

Achieve uniform height for two elements using Material UI

Here is the code snippet I have: <div className="center"> <TextField variant="outlined" className="manualUserFollowTxt" required id="manualUserFollowTxt" label="Username" name="username" autoComplete="username" a ...

Problems with the functionality of the remote feature in Twitter Bootstrap Modal

Utilizing Twitter Bootstrap, I aim to retrieve HTML from another page and inject it into the modal on my current page. This led me to create a JavaScript function to facilitate this process. Within my 'index.php' file, I include the following: ...

What is the technique for performing asynchronous querying of multiple SQL databases?

Currently, I am in the process of developing a web application using nestjs and typeorm. I have been contemplating the functionality of the following code: const r1 = await this.connection.query(sqlA) const r2 = await this.connection query(sqlB) Does th ...

Finding the height of a dynamic div in ReactJS when no CSS height is set

I'm encountering an issue when trying to determine the height of a dynamically created div that doesn't have a defined CSS height property. I'm working with React JS and have attempted to use jQuery, pure JavaScript, and React tools to acces ...

Guide on how to compare two arrays in JavaScript and identify mismatches by their respective indices

let x=["e","f","g","h"]; let y=["f","e","g","h"]; I want the following result: Inconsistent array from x Inconsistency array=["e", "f"]; ...

Effortlessly browse through directory with the seamless integration of AngularJS or

Hey there! I'm working on a really cool feature - creating a list with editable inputs. However, I've encountered a bit of an issue. Is there any way to navigate through this list using arrow keys and focus on the desired input? .content ul { ...

JavaScript code to shift a box beyond the boundaries of a grid

I have a yellow square within a grid. Upon clicking the 'UP' button, the yellow square moves up by one box. How can I ensure that the square stops at the edge of the grid and does not move out? let moveCounter = 0; var grid = document.getElem ...

Fetch data dynamically upon scrolling using an AJAX request

Instead of making an ajax call to load data, I want to do it on scroll. Here is the code I have: $.ajax({ type: 'GET', url: url, data: { get_param: 'value' }, dataType: ' ...

Utilizing an AngularJS custom filter twice

Experimenting with a custom Angular filter example found at: https://scotch.io/tutorials/building-custom-angularjs-filters#filters-that-actually-filter, my version looks like this: <!DOCTYPE html> <html> <script src="http://ajax.googleapi ...