Home Web Front-end JS Tutorial Use store to optimize React components

Use store to optimize React components

Jan 04, 2018 am 10:03 AM
react store 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,
 };
}
Copy after login

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>
  );
 };
}
Copy after login

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:

JS implements clicking on the web page to determine whether to install the app and open it, otherwise jump to the app store

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
How to install the Windows 10 old version component DirectPlay How to install the Windows 10 old version component DirectPlay Dec 28, 2023 pm 03:43 PM

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? PHP, Vue and React: How to choose the most suitable front-end framework? Mar 15, 2024 pm 05:48 PM

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.

How to open the settings of the old version of win10 components How to open the settings of the old version of win10 components Dec 22, 2023 am 08:45 AM

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 front-end React framework Integration of Java framework and front-end React framework Jun 01, 2024 pm 03:16 PM

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.

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

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.

Microsoft Store cannot be opened and displays 'Sorry! Something went wrong, but we got it right' - [Detailed Solution] Microsoft Store cannot be opened and displays 'Sorry! Something went wrong, but we got it right' - [Detailed Solution] Mar 27, 2024 pm 01:21 PM

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

Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

See all articles