React TS- Functional Component with State & Class Component with State.

State in function components

  • To have type-safety for the state in functional components, we don't necessarily need to modify our code: The useState hook inherits the type from the value we use to initialize it.

  • If we use a more complex type or don't initialize the state, we can pass the type like the following:


   React Typescript Functional Component with State.

   import React, { useState } from "react";

   interface IState{
    name:String,
    title:String,
   }

//    interface IPROPS {
//     name : String;
//     title : String;
//    }

    var Customer:React.FC =()=>{
        var [state,setState] = useState<IState>({
            name:'code guruva',
            title:'this is full stack development',
        })
        return(
            <div>
                {/* <h2>this is customer tsx component</h2>
                <h3>Name : {name}</h3>
                <h3>Name : {title}</h3> */}

                <h2>for state values</h2>
                <h3>user name : {state.name}</h3>
                <h3>user name : {state.title}</h3>
            </div>
        )
    }

    export default Customer;

   React Typescript Class Component with State.

   
    import React from "react";

    interface IState{
        myname:String,
        title:String,
    }

    interface IPROPS {
        userid:number;       
    }

    export default class Users extends React.Component<IPROPS,IState>{
        //eslint-disable-next-line
        constructor(props:IPROPS){
            super(props);
            this.state= {
                myname:"code guruva",
                title:"full stack developer"
            }
        }
        render() {
            // destructor
            var {userid} = this.props;
            var {myname, title} = this.state;
            return (
                <div>
                    <h2>Welcome to React TSX Class Component</h2>
                    <h5>UserId : {userid}</h5>
                    <h2>this is state</h2>
                    <h5>Names :{myname}</h5>
                    <h5>Names :{title}</h5>
                </div>
            )
        }
    }