Home Development Tools composer Detailed steps for encapsulating React Context Composer (share)

Detailed steps for encapsulating React Context Composer (share)

Dec 20, 2021 pm 01:57 PM

This article is written by composer Tutorial column to introduce to you how to encapsulate a React Context Composer step by step. I hope it will be helpful to friends in need!

How do I encapsulate a React Context Composer step by step?

Motivation

There are many state management solutions for React, such as Redux, Mobx, Recoil, etc. So far, I have only experienced Redux, and I think it is still a bit cumbersome. . Because I usually write a lot of Hooks, I prefer to use Context Provider with the useContext hook, which makes it easy to split and combine states. Here, we will not discuss the pros and cons of each state management solution, but focus on a multi-layer nesting problem encountered when using Context.

The picture below is some code extracted from a taro react hooks ts project I was writing recently. I split some global state (the purpose of splitting is to reduce unnecessary re-rendering) and then nested them. This way of writing reminds me of the feeling of being dominated by callback hell, which is very uncomfortable. Therefore, I thought of sealing a high-order component myself and "flattening" the structure in terms of writing.

<LoadingContext.Provider value={{ loading, setLoading }}>
  <UserDataContext.Provider value={{ name: "ascodelife", age: 25 }}>
    <ThemeContext.Provider value={"light"}>
    {/* ....more Providers as long as you want */}
    </ThemeContext.Provider>
  </UserDataContext.Provider>
</LoadingContext.Provider>
Copy after login

The easiest solution

Here, I quickly wrote the first solution, using reduceRight to complete the nesting of Provider.

The reason reduceRight is used here instead of reduce is that we are more accustomed to the writing order from the outer layer to the inner layer.

// ContextComposer.tsx
import React from &#39;react&#39;;
type IContextComposerProps = {
  contexts: { context: React.Context<any>; value: any }[];
};
const ContextComposer: React.FC<IContextComposerProps> = ({ contexts, children }) => {
  return (
    <>
      {contexts.reduceRight((child, parent) => {
        const { context, value } = parent;
        return <context.Provider value={value}>{child}</context.Provider>;
      }, children)}
    </>
  );
};
export default ContextComposer;
// App.tsx
<ContextComposer
  contexts={[
    { context: ThemeContext, value: "light" },
    { context: UserDataContext, value: { name: "ascodelife", age: 25 } },
    { context: LoadingContext, value: { loading, setLoading } },
  ]}>
    { children }
</ContextComposer>
Copy after login

After actual experience, I found that although it can be used, the development experience is a little bit worse. The problem is that the value passed when the component enters the parameter is of type any, which means that the static type check of ts is abandoned. When passing parameters, since static type checking will not be done on the value, not only will there not be any code prompts when typing the code, but it may also cause some relatively low-level runtime errors. Bad review!

Transformation plan based on React.cloneElement()

In order to transform the above scheme, I turned to a relatively unpopular but easy-to-use function——React. cloneElement(). There are not many points worth noting about this function. Mainly take a look at its three input parameters. The first is the parent element, the second is the parent props, and the third is the remaining parameters...children, except for the first parameter. Except for this, all other values ​​are optional.

For example:

<!-- 调用函数 -->
React.cloneElement(<div/>,{},<span/>);
<!-- 相当于创建了这样一个结构 -->
<div> 
    <span></span>
</div>
Copy after login

Then let’s start the transformation. The reduceRight frame remains unchanged. Change the input parameter type and reduceRight callback.

// ContextComposer.tsx
import React from &#39;react&#39;;
type IContextComposerProps = {
  contexts: React.ReactElement[];
};
const ContextComposer: React.FC<IContextComposerProps> = ({ contexts, children }) => {
  return (
    <>
      {contexts.reduceRight((child, parent) => {
        return React.cloneElement(parent,{},child);
      }, children)}
    </>
  );
};
export default ContextComposer;
// App.tsx
<ContextComposer
  contexts={[
      <ThemeContext.Provider value={"light"} />,
      <UserDataContext.Provider value={{ name: "ascodelife", age: 25 }} />,
      <LoadingContext.Provider value={{ loading, setLoading }} />,
  ]}>
    { children }
</ContextComposer>
Copy after login

After the transformation, when we pass parameters, it seems that we are really creating a component (of course, the component is actually created, but the component itself is not rendered to the virtual Dom, and is actually rendered. is a cloned copy). At the same time, the static type checking problem of value that we just focused on has also been solved.

tips: React.cloneElement(parent,{},child) is equivalent to React.cloneElement(parent,{children:child}), do you know why?

Related resources

The source code has been synchronized to github (https://github.com/ascodelife/react-context-provider-composer).

It has also been packaged into the npm warehouse (https://www.npmjs.com/package/@ascodelife/react-context-provider-composer). Welcome to experience it.

The above is the detailed content of Detailed steps for encapsulating React Context Composer (share). 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

What is a composer used for? What is a composer used for? Apr 06, 2025 am 12:02 AM

Composer is a dependency management tool for PHP. The core steps of using Composer include: 1) Declare dependencies in composer.json, such as "stripe/stripe-php":"^7.0"; 2) Run composerinstall to download and configure dependencies; 3) Manage versions and autoloads through composer.lock and autoload.php. Composer simplifies dependency management and improves project efficiency and maintainability.

What is a composer doing? What is a composer doing? Apr 08, 2025 am 12:19 AM

Composer is a dependency management tool for PHP, used to declare, download and manage project dependencies. 1) Declare dependencies through composer.json file, 2) Install dependencies using composerinstall command, 3) parse the dependency tree and download it from Packagist, 4) generate the autoload.php file to simplify automatic loading, 5) optimize use includes using composerupdate--prefer-dist and adjusting the autoload configuration.

What is the difference between composer and orchestrator? What is the difference between composer and orchestrator? Apr 02, 2025 pm 02:49 PM

Composer is used to manage dependencies on PHP projects, while Orchestrator is used to manage and coordinate microservices or containerized applications. 1.Composer declares and manages dependencies of PHP projects through composer.json file. 2. Orchestrator manages the deployment and extension of services through configuration files (such as Kubernetes' YAML files), ensuring high availability and load balancing.

Composer Expertise: What Makes Someone Skilled Composer Expertise: What Makes Someone Skilled Apr 11, 2025 pm 12:41 PM

To become proficient when using Composer, you need to master the following skills: 1. Proficient in using composer.json and composer.lock files, 2. Understand how Composer works, 3. Master Composer's command line tools, 4. Understand basic and advanced usage, 5. Familiar with common errors and debugging techniques, 6. Optimize usage and follow best practices.

What is composer in Android? What is composer in Android? Apr 04, 2025 am 12:18 AM

Composer is part of the SurfaceFlinger service in Android, and is responsible for synthesising multiple graphics layers into the final display buffer. 1) Collect the graphics layer, 2) sort the graphics layer, 3) synthesize the graphics layer, 4) output to the display device to improve application performance and user experience.

What is App composer? What is App composer? Apr 07, 2025 am 12:07 AM

AppComposer is a tool for building and managing applications. 1) It simplifies application development and improves efficiency by dragging and configuring predefined components. 2) Developers can define components, combine interfaces, define business logic, and ultimately render the application. 3) Support basic and advanced usage, such as task management and conditional rendering, helping to build flexible applications.

What is the definition of a composer? What is the definition of a composer? Apr 03, 2025 am 12:17 AM

Composers are people who make music, express emotions, tell stories, and convey ideas through music. The composer's work includes: 1. Concept: determine the theme and style of the work; 2. Creation: compose melody and harmony to form a preliminary musical structure; 3. Experiment: audition and adjustment of the work through instruments or software; 4. Improvement: modify and improve according to the audition results until you are satisfied.

The Path to Becoming a Composer: A Practical Guide The Path to Becoming a Composer: A Practical Guide Apr 13, 2025 am 12:11 AM

The steps to becoming a composer include: 1. Master the basic elements of music, such as notes, rhythm, harmony, and melody; 2. Select appropriate technical tools, such as AbletonLive; 3. Understand the process of composing, including inspiration acquisition, conception, writing, modification and improvement; 4. Start with simple melody creation and gradually try complex techniques such as harmony; 5. Solve common problems through debugging techniques, such as note selection and rhythm arrangement; 6. Apply performance optimization and best practices, such as using templates, version control, and collaboration.

See all articles