Use store to optimize React components
This article mainly introduces the method of using store to optimize React components. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
When writing components using React, we often encounter situations where two different components need to share state, and the usual approach is to promote the state to the parent component. But there is a problem with this, that is, although only two components need this state, because the state is mentioned to the parent component, when the state changes, the parent component and all sub-components below it will be re-rendered. If your The parent component is relatively complex and may cause performance problems if it contains many other sub-components.
Redux puts the state in the global store, and then the components subscribe to the state they need. When the state changes, only those components whose subscribed state changes will be re-rendered, thus avoiding The side effects of the improved status mentioned above. However, when we are writing a React component library, the combination of redux and react-redux may be a bit too heavy. So we can write a simple store ourselves to implement a subscription model similar to Redux.
Refer to the implementation of Redux to write a simplified version of createStore:
function createStore(initialState) { let state = initialState; const listeners = []; function setState(partial) { state = { ...state, ...partial, }; for (let i = 0; i < listeners.length; i++) { listeners[i](); } } function getState() { return state; } function subscribe(listener) { listeners.push(listener); return function unsubscribe() { const index = listeners.indexOf(listener); listeners.splice(index, 1); }; } return { setState, getState, subscribe, }; }
Our createStore is very simple. There are only 33 lines including blank lines, and the total is exposed There are 3 methods. There is no dispatch and reducer in Redux. The state is changed directly through the setState method. Let's use it as an example of a counter.
class Counter extends React.Component { constructor(props) { super(props); // 初始化 store this.store = createStore({ count: 0, }); } render() { return ( <p> <Buttons store={store} /> <Result store={store} /> </p> ) } } class Buttons extends React.Component { handleClick = (step) => () => { const { store } = this.props; const { count } = store.getState(); store.setState({ count: count + step }); } render() { return ( <p> <button onClick={this.handleClick(1)}>+</button> <button onClick={this.handleClick(1)}>-</button> </p> ); } } class Result extends React.Component { constructor(props) { super(props); this.state = { count: props.store.getState().count, }; } componentDidMount() { this.props.store.subscribe(() => { const { count } = this.props.store.getState(); if (count !== this.state.count) { this.setState({ count }); } }); } render() { return ( <p>{this.state.count}</p> ); }; }
In the example, changing the state in the store through store.setState in Buttons will not cause the entire Counter to be re-rendered, but because the Result is subscribed to the store changes , so when the count changes, you can re-render by changing the state in your component, thus cleverly avoiding unnecessary rendering.
Finally, although the above createStore only has a few dozen lines of code, I still wrote it into a library called mini-store and put it on GitHub, and provided a Redux-like Provider and connect method, which adds up to Just over 100 lines of code. If you are also writing a React component library and need to manage the state of a complex component, you might as well try this optimization method.
Related recommendations:
Ecstore gets dbschema content?
A brief discussion on the style of react isomorphism straight out
The above is the detailed content of Use store to optimize React components. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

Win10 old version components need to be turned on by users themselves in the settings, because many components are usually closed by default. First we need to enter the settings. The operation is very simple. Just follow the steps below. Where are the win10 old version components? Open 1. Click Start, then click "Win System" 2. Click to enter the Control Panel 3. Then click the program below 4. Click "Enable or turn off Win functions" 5. Here you can choose what you want to open

Integration of Java framework and React framework: Steps: Set up the back-end Java framework. Create project structure. Configure build tools. Create React applications. Write REST API endpoints. Configure the communication mechanism. Practical case (SpringBoot+React): Java code: Define RESTfulAPI controller. React code: Get and display the data returned by the API.

Vue component development: Progress bar component implementation method Preface: In Web development, the progress bar is a common UI component, often used to display the progress of operations in scenarios such as data requests, file uploads, and form submissions. In Vue.js, we can easily implement a progress bar component by customizing components. This article will introduce an implementation method and provide specific code examples. I hope it will be helpful to Vue.js beginners. Component structure and style First, we need to define the basic structure and style of the progress bar component.

Vue component practice: Introduction to paging component development In web applications, the paging function is an essential component. A good paging component should be simple and clear in presentation, rich in functions, and easy to integrate and use. In this article, we will introduce how to use the Vue.js framework to develop a highly customizable paging component. We will explain in detail how to develop using Vue components through code examples. Technology stack Vue.js2.xJavaScript (ES6) HTML5 and CSS3 development environment
![Microsoft Store cannot be opened and displays 'Sorry! Something went wrong, but we got it right' - [Detailed Solution]](https://img.php.cn/upload/article/000/887/227/171151687965989.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Some users want to find their favorite apps in the Microsoft Store and download and install them, but find that the Microsoft Store cannot be opened, and it also prompts "Sorry! Something went wrong, but we did it right." So how should we solve it so that it can be opened? Is the Microsoft Store back up and running? The editor has compiled two methods below, I hope they can help you very well! Method one can press Win+R→enter cmd and then hold down ctrl+shift→click OK (click Yes after UAC pops up) and then the cmd window pops up (administrator mode) and then copy and paste the following content: netshwinsockresetnetshintipresetipconfig/releaseipconfig/renewi
