Learn from the new React documentation

React Docs Beta

The React based

  • JSX braces: Window to get global variables

  • Props is a read-only snapshot, and each render receives a new Props object

  • Event Handlers and useEffect perform side effects

  • The three types of input data, props, state, and context, are treated as read-only

  • React’s strict mode calls render twice on each component at development time to find components that have side effects, and the result of the second call is discarded

  • There are two reasons for component updates: the initial render triggered by the call to reactdom.render and the state update rerender

  • React calls our component, the initial render calls the root component, and the subsequent render calls the state update component

  • The Render function needs to be pure

  • The changes are submitted to the DOM with initial render calling appendChild followed by the minimal update set

  • React waits for the Event Handlers code to execute before handling status updates

  • React does not batch across events; each event is processed individually

State

basis

  • State updates are triggered for two types of reasons: user input (button click, input, jump), computer input (network request return, timer completion, image loading completion)

  • User input generally needs to be processed by an Event Handler

  • State updates the queue internal implementation

export function getFinalState(baseState, queue) { let finalState = baseState; for (let update of queue) { if (typeof update === 'function') { // Apply the updater function. finalState = update(finalState); } else {Replace the next state., finalState = update; } } return finalState; }Copy the code

The principle,Easy to update and reduce errors)

  1. Combine related state variables: If you always update several state variables at the same time, consider combining them into a single state variable. Or you don’t know the number of state variables, such as form data

  2. Avoid mutually exclusive state variables: Avoid errors if several state variables are mutually exclusive

  3. Avoid redundant state variables: If it is information that can be calculated from existing state variables, props, URLS, cookies, localStorage, etc., it does not need to be in state. Values that do not change, and values passed by props, should not be placed in state

  4. Avoid duplicate state variables: If the same information is repeated across multiple state variables, urls, and storages, it can be difficult to keep them in sync. So avoid duplicate state variables

  5. Avoid deeply nested state variables: State variables that are too deeply nested are not easy to update. So it’s best to keep the state result flat

  6. For selected items, use selectedId or selectedIndex instead of selecting the item object

  7. Ensure a single source for the state variable

use

  • Remove any unnecessary state: is this state a subset of another state? Can you get the same information from another state

State is reserved and reset

  • React only preserves the state of components that are being rendered in the UI tree. Once a component is removed from the UI tree, React destroys the component, discarding its state

  • React treats the same component at the same location in the UI tree as a component

  • State is reset for different components in the same location, and the subtree of that component is destroyed and rebuilt

  • Should not be nested definition component function, if nested definition, each outer render, declaration of different components, affect the React of judgment. So be sure to declare component functions at the top level

  • Don’t keep state for components of the same type in the same location: add keys in different locations

Reducer & Context

  • UseReducer: Use curly braces for cases in the Reducer function and return the new state

  • The reducer name comes from the array. reduce parameter name and is called Reducer. The next result is returned based on the result and current data

  • Reducer is to separate the logic of state update

  • Reducer should be a pure function with no side effects

  • The name of the action should say what happened

  • Context, like inheritance of CSS properties, can only be overridden by lower-level Provider values

  • Context Usage scenarios: Topic, current user information, routing, and global status management

  • Use Context with Reducer and put it into a file that includes:

    1. Reducer and initial state
    2. The logic for creating the context
    3. Use children as the Provider component for props
    4. Export the useSomeContext function

Ref

  • Ref: You want the component to remember information, but you don’t want it to change and trigger rerender

  • Ref updates do not cause the component rerender

  • If the information is used to render, put it in state; If the information is only needed by the Event Handler and no render is triggered, use ref

  • Do not read or write ref.current while rendering, use state if necessary. React doesn’t sense the ref.current change

  • Ref internal implementation

// Inside of React
function useRef(initialValue) {
  const [ref, unused] = useState({ current: initialValue });
  return ref;
}
Copy the code
  • Ref usage scenarios handle interactions outside React: store timeout IDs, store DOM elements for operations, and store information that does not participate in JSX calculations

  • Ref changes are updated in time, unlike state snapshots in each render. Because ref is just a normal JS object

  • A ref callback can manage multiple Refs

  • The forwardRef passes the parent component’s ref property to the child component

  • UseImperativeHandle lets you customize the Ref object provided to the parent component

  • FlushSync forces React to synchronize DOM updates

Hooks

basis

  • The essence of Hooks is that they provide the ability for function components to bind to a mutable data source

  • Every UI change is done by re-executing the entire Hooks function

  • Hooks function body code that directly affects the result of render

  • The difference between Hooks and ordinary functions is that there are no other Hooks used in ordinary functions

What problems do the built-in Hooks solve

  • UseState is used to save the status

  • UseEffect is used to perform side effects

  • UseCallback is used for caching functions

  • UseMemo is used to cache calculation results

  • UseRef is used to store data across renderings

  • The useReducer pulls the status update logic out

Specific Hooks

useState

  • Const [state, setState] = useState(” “)setState(

  • Lazy initialization state: The initialization function is called only during initial rendering, avoiding complex computational performance overhead

const [state, setState] = useState(() = > {
  const initialState = someExpensiveComputation(props);
  return initialState;
});
Copy the code

UseEffect: Determine dependencies and perform the appropriate side effects after each component render

parameter
  • UseEffect takes a function as the first argument, which React calls after DOM updates

  • The first argument cannot be an async/await function, because this syntax returns a promise by default

  • In the first argument, you can return an effect-clearing callback that is executed not only at component destruction, but also before each effect re-execution to clean up the result of the previous effect execution

  • UseEffect takes an array dependency as a second argument that controls the conditional execution of effect

Dependencies: Avoid performing meaningless work
  • UseEffect (() => {}) does not declare the second dependency. Render is executed every time

  • UseEffect (() => {}, []) declares an empty array as a dependency. Execute only after the first render

  • UseEffect (() => {}, [deps]) declares an array of dependencies. Executed the first time and after the dependency changes

  • UseEffect () => {return () => {}}, []) declares an array of dependencies and returns a callback function. Effect is executed only after the first render and the callback is executed after the component is unmounted

useCallback

  • UseCallback (fn, [DEps]) redeclares the fn callback only when a dependent variable changes

  • Avoid repeated rendering of child components

useMemo

  • useMemo(() => computeExpensiveValue(a, b), [a, b])Recalculation occurs only when a dependent variable changes

UseRef:

  • Data is shared between multiple renders, storing data across renders

  • The data stored with useRef is generally independent of the RENDERING of the UI, so a change in the ref value does not trigger a re-rendering of the component, which is what differentiates useRef from useState

  • Defining variables outside of the component can cause problems if there are multiple component instances on a page and common variables outside the component are shared

other

  • React uses shallow comparisons to see if dependencies have changed, so pay special attention to arrays or object types. If you create a new object each time, even if the value is equivalent to the previous value, it is considered a dependency change. This is a place where Hooks can easily lead to bugs in the first place

  • Write components in order: simple projects from top to bottom, complex projects from bottom to top