Hello Friends đź‘‹,
Welcome To Infinitbility! ❤️
This tutorial will help you to use interface or DTO in your React useState hook, Below example will work on react and react native both frameworks.
Here we will learn use of interface objects and an array of interface objects in useState.
Let start today’s tutorial How to use interface in React hook useState?
First, take an example of an interface to use in variables.
it’s our interface
interface IUser {
id: number;
name: string;
email: string;
}
and when we want to use it as a referance in new veriable we will use colon syntax.
let newUser:IUser = {
id: 1,
name: "infinitbility",
email: "infinitbility@gmail.com"
};
but now how can the IUser
interface used in our useState. check the Below example.
const [user, setUser] = useState<IUser>({
id: 1,
name: "infinitbility",
email: "infinitbility@gmail.com"
});
Now, move to the next level how we can define an array of interfaces in useState.
const [user, setUser] = useState<Array<IUser>>([{
id: 1,
name: "infinitbility",
email: "infinitbility@gmail.com"
}]);
Thanks for reading…