preface

Take the initiative to roll up, each major public account has introduced 18, these days use off work time specially play, and make a record. React18 git position

Build tools

Build tools to try vite, can’t resist curiosity, try more, learn more

  • Vite is a Web development build tool developed by the authors of VUE
  • Server based on browser native ES module import
  • In a development environment, the import is parsed in the browser and compiled on the server on demand, bypassing the concept of packaging altogether
  • The server is available on demand
  • React and OK support for Vue files as well as hot updates, which do not slow down as modules grow

Vite official website explains

Project initialization

  • npm init -y
  • npm install react@alpha react-dom@alpha @types/react @types/react-dom -S
  • npm install vite typescript @vitejs/plugin-react-refresh -D
  • npm install react-router-dom @types/react-router-dom

File structure

Configuration file

tsconfig.json

{"compilerOptions": {include": ["./ SRC ", "SRC /routes/.tsx"]}Copy the code

vite.config.ts

I was shocked when I wrote it. It's so simple

  • The main configuration is a hot update plug-in
import { defineConfig } from "vite";
import reactRefresh from "@vitejs/plugin-react-refresh";
export default defineConfig({
  plugins: [reactRefresh()],
});

Copy the code

package.json

  • The command configuration
 "scripts": {
    "dev": "vite",
    "build": "tsc && vite build"
  },
  
Copy the code

Entrance to the file

  • src/main.tsx
  • index.html
    1. Type =”module” You can import es6 modules and enable the ESM mechanism

Project start

  • The test results

New features

1.Automatic batching batch updates

Output of setState in different modes

state = { number: 0 }; handleClick = () => { const { number } = this.state; this.setState({ number: this.state.number + 1, }); console.log(this.state); // Synchronization mode: 0; 0 this.setState({number: this.state.number + 1,}); console.log(this.state); // Synchronization mode: 0; SetTimeout (() => {this.setState({number: this.state.number + 1,}); console.log(this.state); // Synchronization mode: 2; 1 this.setState({number: this.state.number + 1,}); console.log(this.state); // Synchronization mode: 3; Batch mode: 1});Copy the code

Legacy Mode (old mode)

  • React Internally, status updates are pushed to a queue or updated immediately depending on the status of isBatchingUpdate
  • IsBatchingUpdate Default false Normal seState is true if state updates are triggered and state is pushed to the update queue waiting for batch updates (asynchronous updates)
  • If setState is called in native JS, isBatchingUpdate is false, and the state waiting to be updated is executed in advance. Based on this, the new state is updated immediately (synchronous update).

Concurrent mode

Optional mode for 18: Concurrent mode

  • In any case setState is an asynchronous batch update, right
  • Each status update has its own task priority, and updates with the same priority are merged. A smaller value indicates a higher priority (digression)
  • Concurrent mode, setState in setTimeout and normal setState, have the same priority and are merged.

summary

Concurrent mode determines the same priorities according to priority. The setState of the native call is also merged.

Suspense container Components

Suspense is already available in React 18, but the Update fully supports Suspense for lazy loading of components that rely on asynchronous data.

Call way

  • The Suspense Fallback property is used for component UIs when render waits
  • Suspense default loading is false so render children<User/>
    <Suspense fallback={<div>loading</div>}>
       <User />
   </Suspense>
Copy the code

In Suspense, you can write an ErrorBoundary to handle errors in data requests using getDerivedStateFromError

Children Use

  • Rely on an asynchronous data loading method called createresource.read ()
let userResource = createResource(fetchUser(1)); function User() { let { success, data, error }: any = userResource.read(); if (success) { let { id, name } = data; return ( <div> {id} {name} </div> ); } else {return <div> data error </div>}}Copy the code

An asynchronous request

  • CreateResource Default Pending; The exception logic is thrown into the promise and executed. The exception can be caught by componentsDidCatch inside Suspense components
  • ComponentsDidCatch catches an exception and tells whether the exception is a promise. Yes setState loading is true and renders fallback loading state<div>loading</div>)
  • At the end of Suspense component loading state is not false, regardless of the outcome of the promise execution, so render is triggered in Suspense <User />
function fetchUser(id: number) { return new Promise((resolve, reject) => { setTimeout(() => { // resolve({ success: true, data: { id: 1, name: "zoe" + id } }); Reject ({success: false, error: "data load failed"}); }); }); } function createResource(promise: Promise<any>) { let status = "pending"; let result: any; return { read() { if (status === "success" || status === "error") { return result; } else { throw promise.then( (data: any) => { status = "success"; result = data; }, (error: any) => { status = "error"; result = error; }); }}}; }Copy the code

I don't know how to record the screen. HMM.. Imagine for yourself

summary

CreateResource first goes to the exception logic, executes the promise, the promise changes the success state and returns the result of the promise, render

3.SusPenseList

  • Suspense is built on top of Suspense and can support multiple loads
  • The revealOrder attribute determines the data to show in Suspense
    1. Forwards: top down (according to the top down of the writing position, if the front returns slowly, it will be displayed together with the back)
    2. Together: The default value is “Together”
    3. Backwards: display backwards from bottom to top
  • tail
    1. Collapsed shows who dies.
    2. Hidden is not loaded for unlimited time, loaded only to display
     <SuspenseList revealOrder="forwards" tail="hidden">
        <Suspense fallback={<div>1.loading</div>}>
          <User id={1} />
        </Suspense>
        <Suspense fallback={<div>2.loading</div>}>
          <User id={2} />
        </Suspense>
        <Suspense fallback={<div>3.loading</div>}>
          <User id={3} />
        </Suspense>
      </SuspenseList>
Copy the code

Make it your own. I don't know how to record yet

4.StartTransition

Used for non-emergency updates

Example: Input field render1000 data at the bottom according to the input field content, the page will be temporarily unresponsive when the user enters. StartTransition can achieve smooth UI render

  • Callbacks in startTransition are tasks that need to be enabled for gradual update to lower the priority of the operation.
  • If other user operations are performed, the current operation is performed first.
  • Then the callbacks in startTransition are performed, followed by Automatic batching for state merge updates to optimize high-frequency operations with large amounts of data
  • To do this, lower the task priority of setSomething,
 startTransition(() => setSomething());
Copy the code

StartTransition is recommended to explain the principle of the article

5.UseDeferredValue

Let’s use the example from StartTransition

  • UseDeferredValue is a simple way to delay state updates

UseDeferredValue is the startTransition

const [keyword, setKeyword] = useState<string>("");
  const deferredText = useDeferredValue(keyword);
  const handleChange = () => {
    setKeyword(event.target.value);
  };
Copy the code

6. UseTransition double buffer

  • UseTransition, which allows components to wait for content to load before switching to the next screen to avoid unnecessary loading states
  • UseTransition, which allows components to defer slower data acquisition updates to later renderings so that more important updates can be rendered immediately
  • UseTransition uses two separate objects to store the data that needs to be rendered, one for display directly, and one for storage after receiving the data changes. The two objects are displayed alternately in the user interface
  • UseTransition hook returns an array of two values
    1. StartTransition is a callback function that tells React what state to defer
    2. IsPending is a Boolean value that tells us whether we are in transition waiting for data updates and can be used to make display judgments about the transition UI
export default function () { const [resource, setResource] = useState(initialResource); const [isPending, startTransition] = useTransition(); Return (<div> <User resource={resource} /> {/* button onClick={() => {startTransition(() =>) setResource(createResource(fetchUser(2)))); }} > next user </button> {isPending? <div> loading... </div>:null} </div> ); }Copy the code

summary

When I set the fetchUser request time to 3 seconds, the user switching effect will also wait 3 seconds before switching, and then use isPending to judge the loading transition,…. Am I opening it the wrong way? I don’t think this API works

React18 Alpha Demo address

Finally, the code word is not easy. If you find this article helpful, please remember to like three lianoh. Thank you very much