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>
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 'react'; 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>
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>
Then let’s start the transformation. The reduceRight frame remains unchanged. Change the input parameter type and reduceRight callback.
// ContextComposer.tsx import React from 'react'; 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>
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!

The key steps to identifying a composer include: 1) analyzing the composer's stylistic characteristics, such as Beethoven's drama and power; 2) understanding the composer's historical background and cultural influence, such as Bach's Baroque style; 3) comprehensively analyzing the melody, harmony, rhythm and structure of the work to avoid misjudgment caused by relying solely on a single element.

Composer'sfutureinPHPdevelopmentwithAIincludes:1)AI-enhanceddependencymanagementforsuggestinglibraries,2)AI-drivencodegenerationfortailoredboilerplate,and3)predictivemaintenanceforupdatesandpatches,butfaceschallengeslikedataprivacyandAIbias.

Becoming a successful composer requires skills such as music theory, instrumental performance and sound design, as well as keen inspiration to capture and constant work modification. Composers use these skills and traits to transform emotions and thoughts into musical works, which resonates with their listeners.

Composer proficiency can be evaluated in the following four aspects: 1) Understand basic concepts, such as packages, dependencies and version control; 2) Master core functions, including parsing composer.json, solving dependencies, downloading packages and generating autoload files; 3) Proficient in using basic and advanced commands, such as composerinstall, update, require, and dump-autoload; 4) Apply best practices, such as using composer.lock files, optimizing autoload configuration, and regularly cleaning caches.

Use Composer to combine AI to achieve automated tasks. 1. Composer manages dependencies through configuration file, and AI can optimize version selection. 2. In practical applications, AI can be used to automate dependency management, testing and deployment. 3. Performance optimization includes dependency loading and caching strategies. 4. Pay attention to issues such as version conflicts and AI misjudgment. Through these methods, AI can improve work efficiency and intelligence.

ComposerwithAI is a tool that uses AI to improve the programming experience. 1) It provides real-time suggestions and bug fixes by analyzing code structure, syntax and pattern. 2) Advanced features include code refactoring, performance optimization and security checking. 3) When using, you can adjust the configuration, provide feedback and combine other tools to solve common problems.

Composer is a dependency management tool for PHP, which is used to manage libraries and packages required by projects. 1) It defines dependencies through composer.json file, 2) installs and updates using command line tools, 3) automates the dependency management process, improves development efficiency, 4) supports advanced functions such as dynamically adding dependencies and automatic loading, 5) Ensures consistency of the team environment through composer.lock file.

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json and composer.lock files. 1. Create the composer.json file and run the composerinstall installation dependency. 2. Use composerrequire to add new dependencies. 3. Configure autoload to implement automatic loading of classes. 4. Use composerdiagnose to check the health status of the project. 5. Optimize dependency management: specify the package name update, use composerdump-autoload-o to optimize the autoloader, use composerinstall--no-d in the production environment


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
