It's been a long time since I wrote a technical article about React, and React has also released its latest version, 19. Today I reread the official React website. Record the key points and new things I've learned.
This article is a personal note, reflecting my own gaps in understanding React, so it is not recommended for reading.
| - | - |
|---|---|
| small projects | it’s usually easier to go top-down |
| larger projects | it’s easier to go bottom-up. |
Which of these are state? Identify the ones that are not:
Props vs State
one-way data flow, the data flows down from top-level component to the ones at the bottom of the tree.
How to identify where your state should live?
Create React App has been deprecated. For more information, see Sunsetting Create React App.
next.js is a full-stack framework
React Router is the most popular routing library for React and can be paired with Vite to create a full-stack React framework.
Next.js’s App Router bundler fully implements the official React Server Components specification
Routing
React Router, Tanstack RouterData Fetching
Q: Why React recommends prefetching data in router loaders ?
A: for faster pre-fetching and better performance,
fetching data directly in components can lead to slower loading times due to network request waterfalls.
mitigate slow loading
Splitting code by route, when integrated with bundling and data fetching, can reduce the initial load time of your app
Q: What's the different between SSR and RSC
| - | SSR | RSC |
|---|---|---|
| definition | Server-Side Rendering | React Server Components |
| Goal | Generate a fully rendered HTML page on the server for initial page load (to improve SEO, performance, and user experience) | Split component execution between server and client to reduce client bundle size and improve performance (especially on slow devices/ networks). |
| Key focus: | Solves the "empty white screen" problem improves SEO | Offload heavy work (e.g., data fetching, large libraries) to the server, so the client downloads less JavaScript. |
| critical distinction | Runs all components on the server during initial load. Client-side hydration runs all components again (in the browser) to add interactivity. | Runs server components only on the server (never sent to the client). Client components run only in the browser (sent as JS bundles). |
| Data Fetching | Data fetching happens on the server (during initial render) to populate the HTML. | Data fetching happens directly in server components (on the server), at the component level. |
| Bundle Size | The client downloads the entire JavaScript bundle for the app (since hydration requires re-rendering all components) | The client downloads only client components (marked 'use client'). Server components are not sent to the client (their code stays on the server). |
use React for an entire subroute
Using React for a part of your existing page
split your code into modules with the import / export syntax, and use packages (for example, React) from the npm package registry.
There is quite an expansive set of types which come from the @types/react package
You can find them in React’s folder in DefinitelyTyped. We will cover a few of the more common types here.
There are many types of events provided in the React types - the full list can be found here which is based on the most popular events from the DOM.
If you need to use an event that is not included in this list, you can use the React.SyntheticEvent type, which is the base type for all events.
two common paths to describing the children of a component
the difference between React.ReactNode and React.ReactElement
Style Props
React.CSSProperties
Further learning
TODO
JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information.
a converter: transform HTML into JSX
Keeping components pure
A pure function:
The names of React components must start with a capital letter or they won’t work!
JSX pitfall: Without parentheses, any code on the lines after return will be ignored!
pitfall
summary
JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.
As the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is why in React, rendering logic and markup live together in the same place—components.
Keeping a button’s rendering logic and markup together ensures that they stay in sync with each other on every edit.
JSX and React are two separate things. They’re often used together, but you can use them independently of each other. JSX is a syntax extension, while React is a JavaScript library.
JSX is stricter and has a few more rules than HTML
aria-* and data-* attributes are written as in HTML with dashes.Pro-tip: We recommend using a converter to translate your existing HTML and SVG to JSX.
Why do multiple JSX tags need to be wrapped?
JSX looks like HTML, but under the hood it is transformed into plain JavaScript objects. You can’t return two objects from a function without wrapping them into an array. This explains why you also can’t return two JSX tags without wrapping them into another tag or a Fragment.
Where to use curly braces?
You can only use curly braces in two ways inside JSX:
<h1>{name}'s To Do List</h1> works, but <{tag}>Gregorio Y. Zara's To Do List</{tag}> will not.= sign: src={avatar} will read the avatar variable, but src="{avatar}" will pass the string "{avatar}".double curlies just means pass objects in JSX
Pitfall
Inline style properties are written in camelCase.
For example, HTML <ul style="background-color: black"> would be written as <ul style={{ backgroundColor: 'black' }}> in your component.
Now you know almost everything about JSX:
{{ and }} is not special syntax: it’s a JavaScript object tucked inside JSX curly braces.Forwarding props with the JSX spread syntax, is conciseness
props are immutable
<Avatar {...props} /> JSX spread syntax, but don’t overuse it!<Card><Avatar /></Card> will appear as Card component’s children prop.In React, you can conditionally render JSX using JavaScript syntax like if statements, &&, and ? : operators.
Conditionally returning nothing with null . More often, you would conditionally include or exclude the component in the parent component’s JSX.
Conditional (ternary) operator (? :)
Logical AND operator (&&)
Pitfall
false as a “hole” in the JSX tree, just like null or undefined, and doesn’t render anything in its place.0 is also a falsy valueConditionally assigning JSX to a variable
Recap
{cond ? <A /> : <B />} means “if cond, render <A />, otherwise <B />”.{cond && <A />} means “if cond, render <A />, otherwise nothing”.When and why to use React keys?
Keys tell React which array item each component corresponds to, so that it can match them up later. This becomes important if your array items can move (e.g. due to sorting), get inserted, or get deleted. A well-chosen key helps React infer what exactly has happened, and make the correct updates to the DOM tree.
What do you do when each item needs to render not one, but several DOM nodes?
The short <>...</> Fragment syntax won’t let you pass a key, so you need to either group them into a single <div>, or use the slightly longer and more explicit <Fragment> syntax:
Pitfall
key={Math.random()}.
<Profile key={id} userId={id} />.Why should we keeping components pure ?
Pure functions only perform a calculation and nothing more.
By strictly only writing your components as pure functions, you we avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows.
To get these benefits, though, there are a few rules you must follow.
React assumes that every component you write is a pure function.
Detecting impure calculations with StrictMode
props, state, and context as read-only.if you can’t find the right event handler for your side effect, you can use useEffect. However, this approach should be your last resort.
if you can’t find the right event handler for your side effect, you can use useEffect. However, this approach should be your last resort.
Recap
React use a tree to keep track of your app’s component structure.
Trees are useful tools to understand how data flows through a React app and how to optimize rendering and app size.
Module Dependency Tree
Dependency trees are useful to determine what modules are necessary to run your React app.
When building a React app for production, a tool which is called a bundler, will use the dependency tree to determine what modules should be included.
Q: What is state in React?
A: In React, data that changes over time is called state.
use immer.js
jsimport { useImmer } from 'use-immer';
export default function Form() {
const [person, updatePerson] = useImmer({
name: 'Jack',
// ...
});
function handleNameChange(e) {
updatePerson(draft => {
draft.name = e.target.value;
});
}
return (
<>
<label>
Name:
<input
value={person.name}
onChange={handleNameChange}
/>
</label>
<p>
{person.name}
<br />
is in Beijing
</p>
</>
);
}
Pitfall
All events propagate in React except onScroll, which only works on the JSX tag you attach it to.
In React, this kind of component-specific memory is called state.
Precaution of Hooks
useState is isolated and private
“Rendering” is React calling your components.
During the next step, the commit phase.
Pitfall: Rendering must always be a pure calculation
If you run into a performance issue, there are several opt-in ways to solve it described in the Performance section. Don’t optimize prematurely!
Step 3: React commits changes to the DOM
Recap
本文作者:郭郭同学
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!