009 React & Typescript - CarrieKroutil/Reactivities GitHub Wiki
- React was created by Facebook and is used across many companies and is highly loved by developers.
- It is fast by using a virtual DOM, that maintains a representation of the DOM in memory.
- As well as easy to learn as it is just a library, not a framework.
- The downside though is when needing to do something significant, like adding forms then you need to pull in a forms package of choice.
- Just returns Javascript or Typescript like this app's use case.
Below are specific concepts that make React unique.
React believes that a component should be self-contained with all needed JS, HTML, and CSS to behave and look as desired which makes it very portable to be reused across the app. Each component can maintain its own state, which can be passed down as Props (properties) to child components. Functions can also be passed down to child components, which can affect the state in the parent component.
DOM (domain object model) is represented as a tree data structure and any changes require it to all be re-rendered to take effect, like when using JQuery for example. However, React uses the concept of a virtual DOM, which is a representation of the UI kept in memory and synced with the real DOM by React. Code tells react what state to be in, which tells the virtual DOM, and only the changes (diffs) are applied to the actual DOM which is what makes it very fast.
One-way binding means data can only flow from the react component to the virtual DOM to the DOM, and cannot flow in the opposite direction like other libraries can. The benefit to this is it is less error-prone and gives the developer more control over the data, as well as easier to debug by only needing to drill into the component itself and not the view of the data in the template where the HTML input on the form might be. To debug in React when a user is typing into an input field, can use the onchange event in React to track of the state for that particular input.
Looks like HTML with a few differences, and is effectively Javascript. Basically, it is a sugar coating on Javascript to make it look like HTML, which makes it easy for devs to learn React if you already know Javascript.
Function components that allow the ability to hook into React state and lifecycle events of a component. Older versions of React used classes, but the concept has been replaced with hooks.
-
useState()
hook tracks the state inside the component itself. -
useEffect()
hook allows the ability to hook into the lifecycle events inside a component, used when mounted, initialized, or unmounted.- This adds a side effect to function so that something happens when the component mounts
-
useWhateverWeWant()
hook for example is custom to reuse state and hooks between components.
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
useEffect(() => {
// Update the document title using the broswer api
document.title = `You clicked ${count} times.`;
});
return (
<div>
<p>You clicked {count} times.</p>
<button onClick{() => setCount(count + 1)}>
Click me
</button>
</div>
}
- Strong typing, helps catch silly mistakes ahead of time.
- Object oriented
- Better intellisense (use VS Marketplace Link: https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-next)
- Access modifiers (removed when compiled into JS to just help at write time)
Example code:
export interface Duck {
name: string;
numLegs: number;
makeSound: (sound: string) => void;
}
const duck1: Duck = {
name: 'huey',
numLegs: 2,
makeSound: (sound: any) => console.log(sound)
}
const duck2: Duck = {
name: 'dewey',
numLegs: 2,
makeSound: (sound: any) => console.log(sound)
}
duck1.makeSound('quack');
export const ducks = [duck1, duck2]
The recent version of React (version 17) has drastically improved in using Typescript.
Example using the demo.ts code in the App.tsx file:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { ducks } from './demo';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
{ducks.map(duck => (
<div key={duck.name}>
<span>{duck.name}</span>
<button onClick={ () => duck.makeSound(duck.name + ' quack')}>Make sound</button>
</div>
))}
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
To run, cd client-app
and then npm start
to see the changes.
Open up the dev tool's console to see the quack messages logged.
Another flavor of the above code, extracted into a component called DuckItem.tsx
import React from 'react';
import { Duck } from './demo';
interface Props {
duck: Duck;
}
export default function DuckItem({duck}: Props) {
return (
<div key={duck.name}>
<span>{duck.name}</span>
<button onClick={ () => duck.makeSound(duck.name + ' quack')}>Make sound</button>
</div>
)
}
Then updating App.tsx to look like:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { ducks } from './demo';
import DuckItem from './DuckItem';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
{ducks.map(duck => (
<DuckItem duck={duck} key={duck.name} />
))}
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Install the React developer tools in your preferred browser, like Chrome. See https://react.dev/learn/react-developer-tools for more information.
Once available, two new tabs will be present - Components and Profiler. Note the color of the icon displays if in dev or production mode.
Check out some videos on YouTube to dig deeper:
- This is the Only Right Way to Write React clean-code - SOLID
- Design patterns in React
- Compound Components in React (Design Patterns)
- Custom Hooks in React (Design Patterns)
- Learn React Hooks: useCallback - Simply Explained!
- Modern Data Fetching in React (Complete Guide)
- How To Debug React Apps Like A Senior Developer
- Error Handling in React (Complete Tutorial)
- All 17 React Best Practices (IMPORTANT!)
- Most Used Design Patterns in React | Learn React Design Patterns in One Video
Testing specific focus: