May 30th is the 10th anniversary of React . I pulled React the latest code, and it doesn't matter. There are already 22 hook . where: react package exports 21 react-dom package exports 1 ( useFormStatus ) this article will talk about the role of React from the perspective of the development of hook over the years. the change of times up to now, the development of React has mainly gone through three periods: CSR period (client rendering period) concurrent period RSC period (server component period) the current 22 hook are also the products of these three periods. CSR period back in 2013, in order to solve the increasingly complex interactions of facebook , jordwalke developed React . After a period of exploration, React gradually formed a set of development mode that satisfies CSR . this development model migrates from ClassComponent to FunctionComponent , resulting in the first batch of hook . These hook are all related to the development mode of CSR . For example: related to the flow of states: useState useReducer useContext related to side effects of treatment: useEffect useLayoutEffect related to improving the degree of freedom of operation: useRef related to performance optimization: useMemo useCallback related to debugging: useDebugValue with the continuous iteration of React , several hook are introduced. In essence, they all aim to improve the development model of CSR and supplement or restrict the existing hook capabilities: useImperativeHandle (control useRef to prevent it from getting out of control) useEffectEvent (a supplement to useEffect capabilities) useInsertionEffect (supplement to useEffect scenarios) useMemoCache (reduce the mental…

June 30, 2023 0comments 1369hotness 0likes Aaron Read all

Today we will learn the design pattern commonly used in JavaScript-- proxy pattern In real life, an agent generally means that handles transactions on behalf of the authorized party . In law, it refers to the expression of intention of the agent, the authorized party, to act legally with a third party in his own name. A legal act committed as a result of authorization may have legal effect directly on the authorized party. that is, when it is not convenient for the customer to access an object directly, a proxy object can be provided for the customer to access. After a series of processing to the request, the proxy object transfers the request to the ontology object. definition provides a substitute or placeholder for each object to control access to it. The stand-in object can process the request in advance and then decide whether to transfer it to the ontology object. there are also many proxy modes, such as protection agents and virtual agents. Protection Agent is used to control access to target objects with different permissions; Virtual Agent refers to delaying the creation of expensive objects until they are really needed. Application scenario when we access an object directly, or when we are dissatisfied with our needs, we can consider using a stand-in object to control the access to that object. Let's look at the virtual proxy mode with an example of image preloading: before use first use a loaded picture to occupy space, then load the picture asynchronously, and then fill it into the img node when…

June 15, 2023 0comments 1262hotness 0likes Aaron Read all

there is a sentence that I believe everyone has heard: the replacement of instant noodles is not the more advanced instant noodles, but the rise of takeout the same phenomenon exists in the front-end domain. As a leader in the front-end cache, React-Query has always had a large audience, and the official React-Query courses have sold 8w + copies. but it is such a hit product that there is a risk of being eliminated. Why on earth? Nature of the front-end cache React-Query is located as front-end cache . If you understand the library from a front-end perspective, you might think of it as an enhanced version of axios . but to understand the nature of this library, we need to start from a back-end perspective. in the view of the back end, the back end is responsible for providing the data, and the front end is responsible for displaying the data, so: how should the front end render after the data is updated? After data invalidation, how should the front end render? In essence, this is a data / cache synchronization problem, but in the SPA era, this problem happens to be left to the front end. however, the back end is inherently closer to the data, and it has an advantage to solve this problem. So as rendering tasks gradually move to the back end, React-Query (or similar libraries) gradually lose market. To sum up: what replaces React-Query is not a more advanced competition, but that the soil in which it exists is gradually disappearing. change of SSR…

May 26, 2023 0comments 1418hotness 0likes Aaron Read all

Preface React Context is a commonly used state management mechanism provided by React to developers. Context can effectively transfer the same state in multi-level components, and can automatically notify each component to update when the status is updated. So how does React Context do this, and why does it need to be so designed? Why do you need Context in React's concept of data management, it has always followed the concept of individual data flow and data invariance. When we need to pass the state from the parent component to the child component, we often need to pass it explicitly through Props, for example: const Father:FC = () => { const [count, setCount] = useState<number>(0) return ( <Son count={count} /> ) } const Son:FC = (props) => { const { count } = props; return ( <span>{count}</span> ) } but what if the parent component needs to pass the state to the child component of the child component, that is, the descendant component? Or does the parent component need to be passed to multiple child components at the same time? Of course, continue to use props for layer-by-layer display transfer can certainly achieve this requirement, but that kind of code is too cumbersome and difficult to maintain, if you can maintain a global variable similar to that in Js in the parent component, wouldn't it be nice for all child components to use this global variable? Yes, that's what Context is for, but it's much more than that. What is Context? Context provides a way to pass data between component…

May 23, 2023 0comments 1332hotness 0likes Aaron Read all

in the article React developer essential skills: master useReducer foundation and application , we discussed the basic knowledge of useReducer in React. In this article, we will discuss the advanced techniques of useReducer. This article will show you how to flexibly use useReducer to manage complex states within and between components in React programs through a more complex "task control component"-- the core operation component of task processing in TODO applications. implementation ideas in TODO applications, the core operation is the various processing logic of "task", including "add task", "delete task", "filter task", "search task" and so on. To make it easier to understand, we only implement the "add task" and "delete task" logic. at the same time, in order to facilitate us to later maintain and expand the function and logic of the "task" operation, we should package it into a separate component. In addition, the "add task" and "delete task" functions of the component should also be exposed for the parent component to call. subcomponents TaskControl this subcomponent should contain the following functions: use useReducer in the component to manage the task list and use useRef to create a reference to get the value of the input box. wraps the component with forwardRef so that the add task and delete task methods in the component can be called from the parent component. defines functions for add tasks and Delete tasks to update the task list. use useImperativeHandle to expose the add task and delete task functions to the parent component for calling. Let's take a look at the…

May 16, 2023 0comments 1266hotness 0likes Aaron Read all

in React, the management of component state is very important. Typically, we can use useState to manage component state. However, using useState can become very tedious if the state becomes more and more complex. At this point, we can consider using useReducer to manage the state. you might ask, why not use Redux? It is true that Redux is an excellent and popular state management tool, but there are some scenarios where Redux is not the optimal solution. For example, our application is very small, and using Redux at this time may bring additional complexity. Another example is to update the status frequently, which may cause a large number of action to be triggered, which adds additional overhead and complexity. Therefore, for similar scenarios, useReducer might be more appropriate. so how do we correctly apply useReducer ? This article will give you the answer. what is useReducer useReducer is a hook function used to manage the state of components in React. Its function is to decompose the state of the component into multiple values, and to provide a predictable and controllable way to update the state, thus making the code clearer and easier to understand. useReducer is defined as follows: const [state, dispatch] = useReducer(reducer, initialState); useReducer accepts two parameters: reducer : a function that accepts the current state and action (action) , returns the new state . In reducer , you can modify the state according to the type of action . initialState : the initial value of the state. useReducer & the return value of nbsp; is an…

May 16, 2023 0comments 1219hotness 0likes Aaron Read all

when we use React to build a user interface, one of the most important concepts is status (state). State can be used to store and manage data in React components, and when the state changes, React automatically re-renders the component to reflect the latest state values. React provides the & nbsp; setState & nbsp; function to update the component state, but we need to pay attention to some details when updating the component state using the & nbsp; setState & nbsp; method. In this article, we will gain an in-depth understanding of the role of state updates and callback functions in React, and how to better control state updates. problems with status updates in React, when we update the state using the & nbsp; setState & nbsp; method, React does not guarantee that it will change immediately. Instead, React may batch multiple & nbsp; setState & nbsp; calls together, and then update the status of the component together at some point. This means that if we access the status immediately after updating it, we may get the old value. to avoid this problem, the setState & nbsp; method provides a callback function that allows us to perform some actions after the state update. We can pass the code we want to execute to & nbsp; setState as a callback function, which is called immediately after the status update, so we can make sure that we are accessing the latest state value. For example: this.setState({count: this.state.count + 1}, () => { console.log('Count updated:', this.state.count); }); The code above uses the &…

May 11, 2023 0comments 1496hotness 0likes Aaron Read all

React Hooks is a new feature introduced by React version 16.8 that allows us to use state and other React features without writing class components. Among them, useState and useEffect are the most commonly used. When using React Hooks, because there are no instances of function components, Hooks relies on closures to access and update state. However, when using Hooks, we need to pay attention to the closure trap problem. what is a closure trap? A closure means that a function can access variables defined outside the function. In React, Hooks functions are also closures, and they can access variables defined outside the function. The closure traps of React Hooks are similar to those of ordinary JavaScript, but because of the design of React Hooks, you may encounter some specific problems when using Hooks. Closure traps in React Hooks mainly occur in two situations: use closures in useState; uses closures in useEffect. closure traps in useState closures are used in useState mainly because the parameters of useState are executed only once when the component is mounted. If we use closures in useState, the values of variables in closures are cached, which means that when we update the state in the component, the values of variables in closures are not updated. in the handleClick function, the setCount function returned by useState is used to update the count status value. Because setCount is defined in the App function, and the handleClick function can access the variables and functions defined in the App function, the handleClick function forms a closure that can access…

May 10, 2023 0comments 1469hotness 0likes Aaron Read all

single data binding in Vue, two-way data binding can be achieved through the v-model instruction. However, there is no concept of instructions in React, and React does not support bidirectional data binding by default. React only supports the transfer of data from the state to the page, but it cannot automatically transfer the data from the page to the state for storage. In React, only single data binding is supported, not bidirectional data binding. If you don't believe me, let's look at the following example: import React from "react"; export default class MyComponent extends React.Component { constructor(props) { super(props); this.state = { msg: "this is the default msg for MyComponent components" }; } render() { return ( <div> <h3>Test component</h3> <input type="text" value={this.state.msg} /> </div> ); } } In the code above, we try to read the value of state.msg in the input text box, but a warning pops up in the run result: Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`. Bidirectional data binding is implemented through the onChange method if you bind value attributes to a form element, you must also bind readOnly for the form element, or provide the onChange event: if you bind readOnly, it means that the element is read-only and cannot be modified. At this point, the console will not pop up a warning. if you are binding onChange, it means that the value of…

May 9, 2023 0comments 1295hotness 0likes Aaron Read all

when a React application logic becomes complex, the time taken by the component render increases significantly. If it takes too long to render from the component render to the view, the user will feel the page stutter. there are two ways to solve this problem: change the process of the component render from synchronous to asynchronous, so that the render process page does not get stuck. This is the principle of concurrent updates reduce the number of components requiring render , which is often referred to as React performance optimization usually, we take the above different approach for different types of components. For example, for input boxes with time-consuming logic such as the following, method 1 is more appropriate (because concurrent updates reduce stutters at input): function ExpensiveInput({onChange, value}) { // time-consuming operation const cur = performance.now(); while (performance.now() - cur < 20) {} return <input onChange={onChange} value={value}/>; } so, can you take into account both of these two ways at the whole application level? The answer is-- not really. this is because, for complex applications, concurrent updates are often contrary to performance optimization. That's what this article is about-the concurrency paradox. start with performance optimization for a component, if you want it not to be render , the basic condition that needs to be achieved is that the reference of props remains unchanged. for example, in the following code, Child components depend on fn props . Because fn is inline, references change every time App > component render , which is not conducive to Child performance optimization: function App()…

May 5, 2023 0comments 1265hotness 0likes Aaron Read all
12