- React useState Hook Typescript
- Using typescript
- The React useState Hook Definition
- Use Primitive Types With React useState Hook in TypeScript
- Use User-Defined Interfaces to the Store States in TypeScript
- Use Arrays in useState Hook in TypeScript
- Conclusion
- Sharing is caring
- React Typescript — useState hook
- React Typescript useState hook with primitive types
- React typescript useState object example
- React typescript useState Array of objects.
React useState Hook Typescript
To use the useState hook, you need to know a few things. You can check the figure below to better understand what I’ll explain here.
- You must import it from the React library.
- You must invoke it inside a React component
Code language: JavaScript (javascript)const array = useState(initialValue)
Here we can initialize an array and then access the elements using the array[0] and array[1]. We can use the array[0] element as state and the array[1] element as setState.This is based on a principle in javascript called the destructuring assignment. The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Code language: JavaScript (javascript)const [state, setState] = useState(initialValue)
3. You can then freely render state, or call setState to update your state value.
Code language: JavaScript (javascript)import from 'react' function App< const [state, setState] = useState(1) return( section> div> div> button onClick= => setState(state + 1)>>More button> button onClick= => setState(state - 1)>>Less button> section> ) >
To define a type React.useState() you must add an after typing the word useState and before the opening parenthesis.
Using typescript
Typescript brought great evolution to the JavaScript and ReactJS ecosystem. More productivity, software more robust and reliable, interfaces, and error prediction during development are achievable using TypeScript.
To type the useState hook as an object in React, use the hook’s generic, e.g. const [employee, setEmployee] = useState>() The state variable will only accept key-value pairs of the specified type.
Code language: JavaScript (javascript)import from 'react'; const App = () => < //const employee: const [employee, setEmployee] = useStatename: string; salary: number>>(< name: '', salary: 0, >); useEffect(() => < setEmployee(name: 'James', salary: 100>); >, []); return ( div> h2>Name: h2> h2>Salary: h2> div> ); >; export default App;
We used a generic to type the useState hook correctly while initializing the hook with an object.
Sometimes you might not want to set initial values for all of the object’s properties. In this case, you can mark the properties as optional.
We used a question mark to mark the salary property as optional.
The property can either store an undefined value or a value of type number .
Code language: JavaScript (javascript)const App = () => < // mark salary as optional const [employee, setEmployee] = useStatename: string; salary?: number >>(< name: '', >);
This is why we do not provide it when initializing the state object. If you provide initial values for all of your object’s properties, TypeScript will be able to infer the type of the state variable.
Code language: JavaScript (javascript)import from 'react'; const App = () => < // const employee: // typed correctly without a generic const [employee, setEmployee] = useState(< name: '', salary: 0, >); useEffect(() => < setEmployee(name: 'James', salary: 100>); >, []); return ( div> h2>Name: h2> h2>Salary: h2> div> ); >; export default App;
We passed initial values for all of the object’s properties, which enabled TypeScript to type the employee variable correctly. However, it is a best practice to always explicitly type the useState hook, especially when working with arrays and objects. In some cases, you might not know all of the properties you will set on the object in advance.
Code language: JavaScript (javascript)import from 'react'; const App = () => < // flexible object type const [employee, setEmployee] = useState<
>(<>); useEffect(() => < setEmployee(< name: 'James', salary: 100, department: 'Dev', tasks: ['dev', 'test', 'ship'], >); >, []); return ( div> h2>Name: h2> h2>Salary: h2> div> ); >; export default App;
The
The index signature in the example means that when the object is indexed with a string , it will return a value of any type.
You can use this approach when you don’t know all of the object’s properties in advance.
If you want to set an object property to be one of the multiple types, use a union.
Code language: JavaScript (javascript)import from 'react'; const App = () => < const [employee, setEmployee] = useStatename: string; // string OR number salary: string | number; >>(< name: '', salary: '', >); useEffect(() => < setEmployee(name: 'James', salary: 100>); >, []); return ( div> h2>Name: h2> h2>Salary: h2> div> ); >; export default App;
We used a union to set the salary property to be of type string or number .
If your useState hook gets busy, extract the type you pass to the generic into a type alias or an interface.
Code language: JavaScript (javascript)import from 'react'; type Employee = < name: string; salary: number; >; const App = () => < //const employee: const [employee, setEmployee] = useState(< name: '', salary: 0, >); useEffect(() => < setEmployee(name: 'James', salary: 100>); >, []); return ( div> h2>Name: h2> h2>Salary: h2> div> ); >; export default App;
The React useState Hook Definition
The React useState hook plays an important part when using functional components, from storing temporary data to receiving data from an API call. With the introduction of TypeScript, developer experience has increased manifold.
TypeScript has support for adding types to React useState hook. This is advantageous as TypeScript can infer the types during setting the values and even detect errors in types.
We can mitigate this before to allow safe deployment.
TypeScript has a generic definition for React useState according to the TypeScript React documentations.
Code language: JavaScript (javascript)function useStateS>(initialState: S | (() => S)): [S, DispatchSetStateActionS>>];
Here, S is a generic type. It accepts an initial state, and the hook can accept the state indicated by S , a setState function of type Dispatch> .
Use Primitive Types With React useState Hook in TypeScript
The useState hook can set primitive types in the application state. The primitive types include number , string , and boolean .
Here is an example of how useState can be used for primitive types in TypeScript.
Code language: JavaScript (javascript)const InfoComponent = () => < const [name, setName] = React.useState(""); const [age, setAge] = React.useState(0); const [isMarried, setIsMarried] = React.useState(false); React.useEffect(() => < setName("Geralt"); setAge(95); setIsMarried(false); >, []); return ( <> div>Witcher name : div> div>Age : div> div>Married : div> > ) >
Thus the useState hook has been used for storing the primitive types which are being set in a useEffect hook that gets triggered once when the component is mounted.
Use User-Defined Interfaces to the Store States in TypeScript
Even user-defined interfaces can be used as a type for the useState hook. We can modify the code segment used in the previous section to store the information in an interface so that the code becomes more organized.
Code language: JavaScript (javascript)interface IUser < name : string ; age : number ; isMarried : boolean ; > const InfoComponent = () => < const [ state, setState ] = React.useState(< name : "", age : 0, isMarried : false >); React.useEffect(() => < setState(< name : "Geralt", age : 95, isMarried : false >); >, []); return ( <> div>Witcher name : div> div>Age : div> div>Married : div> > ) >
For setting optional fields in the setState function, the as the keyword can be used for type assertion. We must override the initial state with the optional state attributes passing to the setState function.
Code language: JavaScript (javascript)setState(< . state, . < name : "Geralt", isMarried : "false" > as unknown as IUser >);
Thus in the above example, the age field is not set, and the default value is used, which is provided by the state . The state override is done by the (. ) or the spread operator.
Use Arrays in useState Hook in TypeScript
Arrays can usually be used in useState hooks while getting data from an API. The following code segment demonstrates this while fetching data and displaying it using useState hooks.
Code language: JavaScript (javascript)interface IPost < userId : number ; id : number ; title : string ; body : string ; > export default App = () => < const [ state, setState ] = React.useState
([]); const getPosts = async () => < const res : Response = await fetch( "https://jsonplaceholder.typicode.com/posts"); const posts : IPost[] = await res.json(); setState(posts); > React.useEffect(() => < getPosts(); >, []); return ( <> < state.map( (post,index) =>div key= > h2> h2> div> div> p> p> div> ) > > ) >
Conclusion
This is how we implement React hook useState in TypeScript. So, TypeScript can cleverly infer the type useState in many cases which is great. When TypeScript can’t infer the type we can pass it in as the generic parameter.
Codedamn is the best place to become a proficient developer. Get access to hunderes of practice React.js courses, labs, and become employable full-stack React web developer.
Unlimited access to all platform courses
100’s of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured React.js/Next.js Full-Stack Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Krishnaditya Biswas wrote? Thank them for their work by sharing it on social media.
React Typescript — useState hook
Learn set variable type in useState hook of react typescript, an array of objects primitive types interface type aliases..
React hooks are new features introduced in React Typescript. This tutorial explains about useState hook in React Typescript.
useState hook used to store data in the typescript react component.
Typescript is a typed language, and every value must be declared with type.
So data stored in State must be declared with type explicitly.
Here is a syntax for useState hook
- numbers with zero
- String with «»
- boolean with false
- Array with []
- Objects with an empty object with property values have defaulted.
setProperty with type allows you to accept declared types and avoid runtime errors.
React Typescript useState hook with primitive types
Following are different primitive data types with the useState hook can also be defined with type inference
type is inferred from the default value.
Here, the loading value is inferred as a boolean type, isLoading function takes a boolean value
Here are String and number types
(5000) const [name, setName] = useState("john")
Here is an example to set the string in the useState React hook example.
from 'react'; interface Student < name: string ; marks: number ; >function UseStateExample()< const [message, setMessage] = useState("") // type is string const updateMessage=()=> < setMessage("w3schoolsio") >return ( <> Welcome - >); >; export default UseStateExample;
React typescript useState object example
- Created an interface type for holding the object.
- useState used with type, setting the state accepts object type only
- Default value in the state is assigned with an empty object with default property values.
from 'react'; interface Student < id: number; name: string; >; function UseStateExample()< const [student, setStudent] = useState(); useEffect(() => < setStudent(< id:11, name : "john", >); >, []); return ( <> Welcome
id: - name: >); >; export default UseStateExample;
React typescript useState Array of objects.
- Initial value in useState in one of the following An initialized array of objects with square brackets[].
Another way, State accepts an array of generic types.
from 'react'; interface User < id: number; name: string; >; function UsersComponent()< const [users, setUsers] = useState([]); const addUser=()=> < setUsers(prevUsers =>[ . prevUsers, , ]) > return ( <> Welcome
Listof Users
< return ( > id: - name: ); >)> >); >; export default UsersComponent;