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

in React applications, as the number of components increases, so does the size of the application. This may cause the application to load for too long and bring a bad experience to the user. To solve this problem, we can use component-level demand loading. On-demand loading can improve application performance, reduce page loading time, and improve user experience. In this blog post, I will detail how to implement component-level on-demand loading in React. what is demand loading? on-demand loading (also known as lazy loading) is a technique that allows us to delay loading code until it really needs to be executed. In React applications, demand loading allows us to load components or other resources dynamically when needed, rather than when they are initially loaded. This means that applications can start faster, reduce unnecessary network requests and file sizes, and improve performance and response speed. Why use demand loading? the main reason for using demand loading in React applications is to improve performance and user experience. When we use demand loading, we only load code when needed, not all code when the application starts. This can reduce page loading time and network requests, and improve application response speed and user satisfaction. In addition, demand loading can reduce the file size of the application because we only need to load the necessary code and resources. implementation of demand loading React supports a variety of ways to load components on demand, including using React.lazy and Suspense API, using higher-level components, and using dynamic imports. Now I will introduce the usage of each method…

May 25, 2023 0comments 1574hotness 0likes Aaron Read all

preface The React.cloneElement method is encountered from time to time, and I read the official website documents many times, but I still have little knowledge of how to use it. Therefore, I go deep into the source code layer to find a calling solution. This article will analyze and summarize the usage of React.cloneElement from the source code layer version react source code version: 16.6.1 body usage Clone with element element as template and return new React element. You can modify props, key, ref through config parameter, and child element through children. Any parameter can be passed in React.cloneElement, and will be used as a child element of the new React element starting from the third parameter example import React from "react"; import "./style.css"; export default function App() { const Clone = React.cloneElement(<Temp/>, {key: 123, name: "Zhang San"}, <div>Hello, World 1.</div>, <div>Hello, World 2.</div>) return ( <div> {Clone} </div> ); } const Temp = (props) => { return ( <div> <span>Hello world, {props.name}</span> {props.children} </div> ) }; // Page output Hello world, Zhang San Hello, World.1 Hello, World.2 Parameter analysis element elements of react config object parameter, which can contain the following properties ref: not required to replace ref in the original element key: not required to replace key in the original element other attributes: all props as new element children The child element parameter is more appropriate here. Children parse declare that props, key, ref, self, source, owner are assigned default values based on element const props = Object.assign({}, element.props); // Reserved names are extracted let key = element.key;…

May 24, 2023 0comments 1346hotness 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 1333hotness 0likes Aaron Read all

Reading time is about 6 minutes. We improved the flexibility of React components in " yesterday. Learn more about React's & nbsp in the article "learn more about the wonderful use of forwardRef API " forwardRef & nbsp;API. When we need to manipulate a DOM node in a subcomponent, forwardRef & nbsp; meets our needs very well. But what if we want to manipulate some methods or properties in the subcomponent? you may immediately think of using a callback function to expose the methods or properties that need to be exposed in the child component to the parent component. For example, the following code: import React from 'react'; // Sub-component function ChildComponent(props) { const otherOperate = () => { // some code... } const handleClick = () => { if (props.onClick) { // callback function passed by the parent component props.onClick({ otherOperate }); } }; return ( <button onClick={handleClick}> Click me! </button> ); } // parent component function ParentComponent() { const handleClick = (propsFromChild) => { console.log('Button clicked!', propsFromChild); }; return ( <div> <ChildComponent onClick={handleClick} /> </div> ); } export default ParentComponent; in the above example, we pass the & nbsp; handleClick & nbsp; function as the & nbsp; onClick & nbsp; attribute to the & nbsp; ChildComponent & nbsp; subcomponent. When the button in & nbsp; ChildComponent & nbsp; is clicked, the handleClick & nbsp; function is called, exposing the & nbsp; otherOperate & nbsp; method in the child component to the parent component. In this way, when we click the button of the child component, the parent component…

May 22, 2023 0comments 1267hotness 0likes Aaron Read all

yesterday we discussed the useRef hook function in React: only this article, let you fully master the useRef hook function in React, one of the scenarios is to use useRef in the function component to create a ref object, and then bind it to an element to get a reference to that element in order to do various operations on the referenced element. What do we do when we want to access a reference to a child component in the parent component? The answer is achieved through React's forwardRef API. first acquaintance of forwardRef API forwardRef API allows us to pass a ref from the parent component to the child component, thus giving the parent component access to the DOM node or instance of the child component. The syntax is as follows: const SomeComponent = forwardRef(render); generally speaking, we can let the parent component access the child component through the callback function, that is, pass the callback function to the child component through props to access the DOM node or instance of the child component in the parent component. But in some cases, this approach is not convenient or flexible enough. forwardRef provides a more flexible way to solve this problem. when we wrap the subcomponents with forwardRef , we can access the subcomponents through the second parameter ref of forwardRef . The ref is then passed to the element or component that needs to be referenced in the child component so that the parent component can access the child component's instance or DOM node. This makes forwardRef a very…

May 20, 2023 0comments 1336hotness 0likes Aaron Read all

as the scale of the React application we develop is getting larger and larger, if all the components are still packaged into one bundle file, it may cause the application to load slowly. It is a common practice to package the components in the program into separate files to reduce the load time of the application, which is usually achieved by "loading on demand". In this article, you will learn about the dynamic import of components in React programs. 1.roomnbsp; what is a dynamic import component? dynamic import components refer to loading components when needed, rather than packaging all components into a single bundle file when the application loads. How do we implement it in React? React provides us with a & nbsp; lazy () & nbsp; method and & nbsp; Suspense & nbsp; component, which are the two main tools for dynamically importing components. using & nbsp; React.lazy () , we can easily load components on demand. The syntax is as follows: const MyComponent = React.lazy(() => import('./MyComponent')); in the code above, React.lazy () & nbsp; receives a function that returns a & nbsp; import () & nbsp; function call. import () & the nbsp; function is part of the ECMAScript dynamic import syntax, which allows us to load a module asynchronously at run time. By combining the & nbsp; React.lazy () & nbsp; with the & nbsp; import () & nbsp; function, we can load components on demand. when we use & nbsp; React.lazy () & nbsp;, React automatically wraps the returned component in a & nbsp; lazy…

May 19, 2023 0comments 1484hotness 0likes Aaron Read all

these days we have shared some of React's built-in hook functions, such as useRef, useMemo, useReducer, useImperativeHandle, etc. These built-in hook functions provide great convenience for our development work. In addition to the built-in Hook provided by React, how do we write our own hook functions? Custom Hook allows us to share logic among multiple components, improving code reusability and maintainability. To customize a hook function, we should follow the following rules: Custom Hook must start with use . Custom Hook must be a function, and React's Hook can be used inside the function. Custom Hook must return data or methods. the above three rules must be followed, and they are also mentioned in the official React documentation. Let's use a simple counter example to demonstrate how to customize a general hook function. 1. Define the counter hook function to extract the general logic of a counter into a custom Hook, this hook function should have the following capabilities: can get the value of the current counter; can add value to the counter through the hook function; can reduce the value of the counter through the hook function. based on these three requirements, we can implement the following custom Hook: import { useState } from 'react'; // define the return value type of custom Hook type UseCounterReturnType = [count: number, increment: () => void, decrement: () => void]; // define a custom Hook export default function useCounter(initialCount: number = 0): UseCounterReturnType { // use useState to initialize count state and setCount function const [count, setCount] = useState(initialCount); // define the…

May 18, 2023 0comments 1216hotness 0likes Aaron Read all

Preface friends who know or know Vue all know that in Vue , we can achieve bidirectional data binding of controlled components through v-model , while in React , we need to achieve bidirectional data binding through value and onChange . A single can also be accepted, such as multiple. look at an example. const [nickName, setNickName] = useState('') const [age, setAge] = useState(null) const handleNickNameChange = useCallback((value) => { setNickName(value) }, []) const handleAgeChange = useCallback((value) => { setAge(value) }, []) return ( <> <Input value={nickName} onChange={handleNickNameChange} /> <Input value={age} onChange={handleAgeChange} /> </> ) according to the conclusion above, if there are multiple controlled components in a component, many will be written as above. Can we encapsulate that we only need to declare variables instead of set methods? The answer is OK, you can see below. Tips:input is an uncontrolled component when the value of type is file, because the value is readable when type is file. description what I use here is React + ts . If you use js , you need to delete the type declaration after the variable. withModel the method component I encapsulated here is withModel , which you can name after yourself. //withModel.tsx import React, { forwardRef, useMemo, useCallback, useEffect } from 'react' // two-way binding tool method const withModel = (Component: any) => forwardRef((props, outerRef) => { const p = { models: [], name: '', value: '', onChange: (event: any) => {}, ...props, } const { models = [], name, value, onChange, ...other } = p; const [modelValue, setModelValue] = useMemo(() =>…

May 17, 2023 0comments 1361hotness 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 1267hotness 0likes Aaron Read all
14567812