Common React Optimization Mistakes :👈 👉:JavaScript Closures for React

React with JavaScript and TypeScript

React with JavaScript and TypeScript

1. Introduction

React is a JavaScript library used to build user interfaces. We can develop React applications using either JavaScript or TypeScript.

Both languages support React components, JSX, Hooks, event handling, state management, and other React features.

The main difference is that JavaScript is dynamically typed, whereas TypeScript adds static type checking to JavaScript.

TypeScript helps identify many programming mistakes during development, before the application runs in the browser.

2. What Is JavaScript?

JavaScript is a programming language used to create dynamic and interactive web applications.

React applications can be written directly using JavaScript and JSX.

Example: React Component Using JavaScript

function UserProfile() {
  const name = "John";
  const age = 25;
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
    </div>
  );
}
export default UserProfile;

JavaScript does not require us to declare the data type of variables explicitly.

let age = 25;
age = "Twenty Five"; // Allowed in JavaScript

This flexibility is useful, but accidentally assigning an incorrect value may cause problems later in the application.

3. What Is TypeScript?

TypeScript is a programming language developed by Microsoft. It extends JavaScript by adding static typing and other development features.

TypeScript code is transformed into JavaScript so that browsers can execute it.

In React applications, TypeScript commonly uses the .tsx file extension for files containing JSX and .ts for TypeScript files without JSX.

Example: React Component Using TypeScript

interface User {
  name: string;
  age: number;
}
function UserProfile() {
  const user: User = {
    name: "John",
    age: 25
  };
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Age: {user.age}</p>
    </div>
  );
}
export default UserProfile;

Here, the User interface defines the expected structure of a user object.

If we assign a string to the age property, TypeScript reports a type error during development.

const user: User = {
  name: "John",
  age: "Twenty Five" // Type error
};

4. JavaScript vs TypeScript in React

Feature React with JavaScript React with TypeScript
File extension .js or .jsx .ts or .tsx
Typing Dynamically typed Static type checking
Variable types Usually inferred at runtime Can be declared or inferred during development
Interfaces Not supported as a TypeScript feature Supported
Compile-time type checking No built-in TypeScript checking Supported
Code completion Available, depending on editor analysis Usually more precise with type information
Learning curve Generally easier to start Requires understanding types and interfaces
Large application maintenance Requires additional discipline and testing Types can make refactoring and maintenance easier
Browser execution JavaScript executes in the browser Transformed into JavaScript before browser execution

5. Component Props: JavaScript vs TypeScript

Props are used to pass data from a parent component to a child component.

JavaScript Example

function Welcome(props) {
  return <h2>Welcome, {props.name}</h2>;
}
function App() {
  return <Welcome name="John" />;
}

JavaScript does not automatically enforce the expected type of the name prop.

TypeScript Example

interface WelcomeProps {
  name: string;
}
function Welcome({ name }: WelcomeProps) {
  return <h2>Welcome, {name}</h2>;
}
function App() {
  return <Welcome name="John" />;
}

TypeScript checks that the component receives a string for the name property.

For example, this would produce a type error:

<Welcome name={123} />

6. State Management: JavaScript vs TypeScript

React's useState Hook manages component state in both JavaScript and TypeScript.

JavaScript Example

import { useState } from 'react';
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

TypeScript Example

import { useState } from 'react';
function Counter() {
  const [count, setCount] = useState<number>(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
    </div>
  );
}

Here, useState<number> tells TypeScript that the state should contain a number.

TypeScript can also infer the type from the initial value, so explicitly writing number is not always necessary.

7. Handling Events: JavaScript vs TypeScript

React supports events such as click, change, submit, and keyboard events.

JavaScript Example

function SearchBox() {
  function handleChange(event) {
    console.log(event.target.value);
  }
  return (
    <input
      type="text"
      onChange={handleChange}
    />
  );
}

TypeScript Example

function SearchBox() {
  function handleChange(
    event: React.ChangeEvent<HTMLInputElement>
  ) {
    console.log(event.target.value);
  }
  return (
    <input
      type="text"
      onChange={handleChange}
    />
  );
}

The TypeScript example explicitly identifies the event type. This provides better type checking and editor assistance.

8. Working with API Responses

Applications frequently retrieve data from backend APIs.

JavaScript Example

async function getUser() {
  const response = await fetch('/api/users/1');
  const user = await response.json();
  console.log(user.name);
}

JavaScript does not automatically validate the structure of the returned object.

TypeScript Example

interface User {
  id: number;
  name: string;
  email: string;
}
async function getUser(): Promise<User> {
  const response = await fetch('/api/users/1');
  if (!response.ok) {
    throw new Error('Failed to load user');
  }
  const user: User = await response.json();
  return user;
}

The User interface describes the expected response structure.

Important: Declaring a TypeScript type does not validate actual API data at runtime. For external data, use runtime validation when correctness is important. Libraries such as Zod can help validate API responses.

9. Optional and Required Props in TypeScript

TypeScript allows us to define required and optional component properties.

interface UserProps {
  name: string;
  age: number;
  email?: string;
}
function UserProfile({ name, age, email }: UserProps) {
  return (
    <div>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      {email && <p>Email: {email}</p>}
    </div>
  );
}

Here:

  • name is required.
  • age is required.
  • email? is optional.

10. Common TypeScript Types Used in React

Type Purpose Example
string Text values name: string
number Numeric values age: number
boolean True or false values isActive: boolean
string[] Array of strings names: string[]
interface Defines an object structure interface User { ... }
type Defines a type alias or union type Status = 'active' | 'inactive'
unknown Represents a value whose type is not yet known response: unknown
void Indicates no meaningful return value function log(): void
Promise<T> Represents an asynchronous result Promise<User>

11. Interface vs Type in React

Both interface and type can describe the shape of component props and application data.

Using Interface

interface ProductProps {
  name: string;
  price: number;
}
function Product({ name, price }: ProductProps) {
  return (
    <div>
      <h3>{name}</h3>
      <p>Price: {price}</p>
    </div>
  );
}

Using Type

type ProductProps = {
  name: string;
  price: number;
};
function Product({ name, price }: ProductProps) {
  return (
    <div>
      <h3>{name}</h3>
      <p>Price: {price}</p>
    </div>
  );
}

Both approaches work. Interfaces are commonly used for object contracts, while type aliases are especially useful for unions, intersections, and other type combinations.

12. How to Create a React Application

12.1 React with JavaScript Using Vite

npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev

This creates a React application using JavaScript.

12.2 React with TypeScript Using Vite

npm create vite@latest my-react-app -- --template react-ts
cd my-react-app
npm install
npm run dev

This creates a React application configured for TypeScript.

13. JavaScript or TypeScript: Which Should You Choose?

Situation Recommended Choice Reason
Learning React fundamentals JavaScript Fewer concepts to learn initially.
Small prototype Either Both can support rapid development.
Large enterprise application TypeScript Improves type safety and maintainability.
Multiple developers working together TypeScript Clearer contracts between components and modules.
Complex API data structures TypeScript Provides better development-time type checking.
Existing JavaScript application Either TypeScript can be introduced gradually.

14. Common Mistakes When Using TypeScript with React

1. Using Any Everywhere

Using any disables type checking for the affected value.

function UserProfile({ user }: any) {
  return <h2>{user.name}</h2>;
}

Better: Define an interface or type for the expected data structure.

2. Assuming API Data Is Automatically Validated

Writing const user: User = await response.json() does not verify the actual response at runtime.

Better: Validate external data using runtime validation when required.

3. Making Every Prop Optional

Using optional properties everywhere can make it difficult to understand which values a component actually requires.

Better: Make required properties mandatory and optional properties optional only when appropriate.

4. Ignoring Null and Undefined

API responses and optional properties may contain missing values.

Better: Handle missing values explicitly and enable strict type checking in TypeScript configuration.

5. Using TypeScript Without Understanding JavaScript

TypeScript builds on JavaScript. Understanding JavaScript fundamentals, including variables, functions, arrays, objects, promises, modules, and closures, is important before learning advanced TypeScript features.

15. Recommended Learning Path

  1. Learn JavaScript fundamentals: Variables, data types, functions, arrays, objects, ES6 features, promises, async/await, and modules.
  2. Learn React fundamentals: Components, JSX, props, state, events, and Hooks.
  3. Understand TypeScript basics: Types, interfaces, type aliases, unions, and generics.
  4. Learn TypeScript with React: Component props, state, event types, API response types, and custom Hooks.
  5. Build practical applications: Forms, search interfaces, dashboards, API integrations, and reusable components.
  6. Learn advanced topics: Generic components, utility types, discriminated unions, and runtime data validation.

16. Interview Questions and Answers

Q1. Can we use TypeScript with React?

Yes. React fully supports TypeScript. We commonly use .tsx files for React components containing JSX and .ts files for TypeScript modules without JSX.

Q2. What is the main difference between JavaScript and TypeScript?

JavaScript is dynamically typed, whereas TypeScript adds static type checking. TypeScript helps identify type-related mistakes during development before the code executes.

Q3. Does TypeScript replace JavaScript?

No. TypeScript extends JavaScript and is transformed into JavaScript before browser execution.

Q4. What is TSX?

TSX is a TypeScript file format that supports JSX syntax. It is commonly used for React components written in TypeScript.

Q5. What is the difference between interface and type?

Both define types in TypeScript. Interfaces are commonly used to describe object structures and support declaration merging. Type aliases can describe objects as well as unions, intersections, and other type combinations.

Q6. What is the advantage of TypeScript in large React applications?

It provides better type checking, editor assistance, clearer component contracts, and safer refactoring. It can help teams maintain complex applications more reliably.

Q7. Can we gradually convert a JavaScript React application to TypeScript?

Yes. TypeScript can be introduced gradually by adding TypeScript configuration, installing the required dependencies, renaming selected files to .ts or .tsx, and adding types incrementally.

Q8. Does TypeScript improve React runtime performance?

Not directly. TypeScript primarily improves development-time type safety and maintainability. It does not automatically make the generated JavaScript or React rendering faster.

17. Key Takeaways

  • React supports both JavaScript and TypeScript.
  • JavaScript is a good starting point for learning React fundamentals.
  • TypeScript adds static type checking and improves maintainability.
  • Use .jsx or .js for JavaScript React components and .tsx for TypeScript components containing JSX.
  • Learn JavaScript fundamentals before moving into advanced TypeScript.
  • TypeScript does not automatically validate external API data at runtime.
  • TypeScript does not automatically improve application runtime performance.

Final Recommendation: Learn JavaScript fundamentals first, understand React, and then learn TypeScript with React. This approach builds a strong foundation and prepares you to develop maintainable applications.

🔙
Common React Optimization Mistakes :👈 👉:JavaScript Closures for React

Comments and Discussion