npx create - react - app my - app --template typescript
.Ctrl + Shift + D
on Windows/Linux or Cmd + Shift + D
on Mac).launch.json
file. Select “Chrome” or “Firefox” depending on your browser preference.launch.json
configuration for a React TypeScript project:{
"version": "0.2.0",
"configurations": [
{
"name": "Chrome: React",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000",
"webRoot": "${workspaceFolder}/src",
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
npm start
in the terminal.F5
or click on the green play button in the “Run and Debug” panel. This will open a new browser window with your React application.F10
): Executes the current line and moves to the next one without entering any functions.F11
): If the current line contains a function call, it will enter the function and pause at the first line of the function.Shift + F11
): Exits the current function and continues execution at the line after the function call.F5
): Resumes the execution until the next breakpoint or the end of the program.useState
or useReducer
hooks.import React, { useState } from 'react';
const Counter: React.FC = () => {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1); // Set a breakpoint here to debug state change
};
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
export default Counter;
import React from 'react';
interface Props {
name: string;
}
const Greeting: React.FC<Props> = (props) => {
// Set a breakpoint here to inspect props
return <p>Hello, {props.name}!</p>;
};
export default Greeting;
async/await
or Promise
, set breakpoints inside the async
functions.import React, { useEffect, useState } from 'react';
const FetchData: React.FC = () => {
const [data, setData] = useState<any>(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const jsonData = await response.json();
setData(jsonData); // Set a breakpoint here
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
return (
<div>
{data ? <p>{data.title}</p> : <p>Loading...</p>}
</div>
);
};
export default FetchData;
console.log
statements once you have finished debugging. These statements can clutter the code and may have a performance impact in production.Debugging React TypeScript applications in VS Code is a powerful and efficient way to find and fix bugs in your code. By understanding the fundamental concepts, following the usage methods, and applying common and best practices, you can streamline the debugging process and improve the quality of your React applications. Remember to use breakpoints effectively, keep your code clean, and test in different environments to ensure a robust application.