Class vs Function vs Hooks on TSX
Ever wonder why Typescript is increasing on popularity lately ?
What is behind that ? and Why those are very similar like JSX ?
Let’s get into the topic
So what is TSX ?
TSX standfor Typescript React .
It means it support embeded React element on it .
Yea , as long as you include
import React from 'react';
What is the advantage for Typescript ?
- Typescript provided a static typing , it means enable type checking at compile time , code completion for JSX.
- Code with intellisense for VS Code making code more effective , clean and readability.
- Many library or dependencies that written in Typescript
- A growth community .
Why it’s similiar to Javascript , but somehow it’s different ?
- According to official website : TypeScript is a typed superset of JavaScript that compiles to plain JavaScript . So it’s the same likely as Javascript.
Let’s Start by Code
CLASS
type MyProps = {
message: string;
};
type MyState = {
count: number;
};
class App extends React.Component<MyProps, MyState> {
state: MyState = {
count: 0,
};
render() {
return (
<div>
{this.props.message} {this.state.count}
</div>
);
}
}
Function
type MyProps = {
message: string;
};
or
const MyApp = ({ message }: MyProps) => <div>{message}</div>;
Function with Hooks
export function MyApp() {
const [isLoading, setState] = React.useState(false);
const load = (aPromise: Promise<any>) => {
setState(true);
return aPromise.finally(() => setState(false));
};
return [isLoading, load] as const;
}
The Basic Comparison
function.tsx
function App() {
return (
<div className ="Wrapper">
<Impress hint={false} progress ={true} rootData={{ width: 512 }}>
{/* React */}
<Step>
<div className="center" >
<p style={{marginBottom: -50}}>Apa itu </p>
<h1><b><span className="blue">React</span><span className="yellow">JS ?</span></b></h1>
</div>
</Step>
<Impress>
</div>export default App
class.tsx
class App extends React.Component<any> {constructor(props: any) {
super(props);
}public render() {
return (
<div>
<Impress hint={false} progress ={true} rootData={{ width: 512 }}>
{/* React */}
<Step>
<div className="center" >
<p style={{marginBottom: -50}}>Apa itu </p>
<h1><b><span className="blue">React</span><span className="yellow">JS ?</span></b></h1>
</div>
</Step>
<Impress>
</div>export default App;
So why Typescript is very similar like JS is now solved , now the very first thing is to get dive into a practice and feel the comparison .^_^!