Preface this article shows you how to use React and DOM things to achieve a compelling interactive hover box effect. By hovering over the mouse, the box will randomly change the color and display shadows, adding dynamic and visual appeal to the page. Read this article and you'll learn how to use React to implement event handling and dynamic styling, bringing more interesting interactions to your Web application. scene in modern Web applications, interactivity and dynamic effects are critical to improving the user experience. Hovering effect is a common way of user interaction, when the user hovers the mouse over a specific area, the relevant elements will change to attract the user's attention. In this article, we will explore how to use React to implement a CSS special effect of a hover square effect. Let's take a look at → Development first, import React and some necessary hook functions, as well as the stylesheet we will use in the component. As follows: import React, { useEffect, useRef, useState } from 'react'; import './index.less' The code for the index.less file is as follows: .App { background-color: #111; display: flex; align-items: center; justify-content: center; overflow: hidden; margin: 0; } .container { display: flex; align-items: center; justify-content: center; flex-wrap: wrap; max-width: 600px; overflow: hidden; } .square { background-color: #333; box-shadow: 0 0 2px #000; height: 16px; width: 16px; margin: 2px; transition: 2s ease; } .square:hover { transition-duration: 0s; } then defines an array of colors and a constant SQUARES to set the number of squares. As follows: const colors = ['#861104', '#7611a0', '#127ec7',…

June 1, 2023 0comments 1292hotness 0likes Aaron Read all

Let's talk about the conclusion first useCallback, useMemo, memo, shouldUpdate, performance optimized API, you should not use it without performance problems. Blind use will lead to negative optimization and even delay closure bug. This conclusion is a consensus. but this is only one aspect. I mainly want to talk about it to the point, except for the ideas that API,React really reduces rerender. the coarse granularity of React may hurt innocent people. The agility of jsx, the culprit, makes it difficult for props to distinguish between change and immutability App is a component and Box is a subcomponent const App = ()=>{ return <Box h="200px" w="200px" {/*.....*/}>hello</Box> } // after jsx is compiled const App = ()=>{ return /*#__PURE__*/ React.createElement(Box, { h: "200px", w: "200px" }, "hello"); }; The strategy adopted by React is congruent comparison. Props compares {h: "200px", w: "200px"} in the first time with {h: "200px", w: "200px"} in the second round. Although it seems to be the same, function creates a new object type every time, with a different address, rendering even empty objects, like flood discharge, rendering from the top of the head to the soles of the feet. Box will be rendered const App = () => { return <Box>hello</Box> // Box without memo, still render } // after jsx is compiled const App = () => { // props is an empty object here return /*#__PURE__*/ React.createElement(Box, {}, "hello"); }; this is React's App-level update policy. Why do you adopt such a strategy? Because there are too many props, suppose it is a…

May 31, 2023 0comments 1189hotness 0likes Aaron Read all

there are three front-end framework concepts that are easily confused: responsive updates unidirectional data flow Bidirectional data binding before continuing with this article, readers can think about whether they clearly know the meaning of the three. these three are easy to be confused because although they belong to the same front-end framework, they are not the same level of abstraction, so it is difficult to compare them directly. this article will explain the differences between these three levels of abstraction. responsive updates responsive update is also called fine-grained update . At the same time, the recently popular concept of Signal describes responsive updates . In a nutshell, responsive update describes the relationship between state and UI , that is, how state changes map to UI changes . consider the following example (from what are signals article): function TodoApp() { const [todos, setTodos] = useState( [{ text: 'sleep', completed: false }] ) const [showCompleted, setShowCompleted] = useState(false) const filteredTodos = useMemo(() => { return todos.filter((todo) => !todo.completed || showCompleted) }, [todos, showCompleted]) return ( <TodoList todos={filteredTodos} /> ) } in the TodoApp component, two states are defined: to-do todos whether to show completed items showCompleted and the state derived from the above state filteredTodos . Finally, the & lt;TodoList/> component is returned. if the state of todos changes, how does UI change? That is, how do we know the scope of influence of state changes ? At this point, there are two ideas: push ( push ) pull ( pull ) the principle of push We can start with the changing…

May 27, 2023 0comments 1208hotness 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

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 1345hotness 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

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 1335hotness 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
13456710