Manage Dynamic Components Recharges in React with Metamask
In a recent users, some users face a common challenge you use Metamask Extension in their web application. Wen switching between different networks or accounts, the entire page of the application is recharged, therefore, it can be disappointing to developers who rely on productivity and minimize the love of the page.
In this article we will study a simple React Hoook, which allows you to recharge on it on the component!
The problem:
When the Metamask of the event Chainchanged
, he triggered the all -page render. This can be USR beer that is already engaged in Aslow Network Can or Multi-Multiple accounts in Ther Watchist.
Decision:
Toaddress this problem, we will create a) Here is the code:
`jsx
Import {usestate} by 'react';
CONST INNELADOADCOMPONENT = (componentkey) => {{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{о that
Const [Activecheain, Setactivechain] = usestate (Window.Therumcha [0]);
useeffect (() => {
If (Window.etherum) {
window.etherum.on ('chainchanged', () => {
Tvactivechain (Window.Therumchains.find ((chain) => chain.id === actchain);
});
}
}, [Activechain]);
Return <> {/ component to be recharged /} >;
};
Default Export UsereloadComponent;
Explanation:
In the above code:
- We define the Can Case React Hook
USEERADOCOMPONENT
, which takes away the optimum parameter ‘Componentkey.
- Thehhouk applicationsusstate
hook of the current active chain and its identification number in the variables of local countries (
Activechahahahahaha andActivecheainid &).
- Inuseeffect
Hoook we check is connected. If so, we list the
angle array.
- When an active chain (ie
Activechainid
Changes), we update the ‘Activechain’ status using
- We return the JSX element that the render book converts the active changes of the chain containing the respective component.
Example use:
`jsx
Import reacts 'ACT';
Imports 10./usereeloadComponent ';
Const componenta = () => {
// Make the content of Soome.
};
Const Componentb = () => {
// Make SOOME the content here ...
};
Functional application () {
CONST componentkey = 'Component-A'; // Select the desired component
Const {Activecheain, Setactivechain} = UsereloadComponent (Componentkey);
return (
Active Chain: {Activechain}
);
}
In this example, we define two components (Componenta
and Componentb), which! We are transmitting any Componentkey
to ‘UsereloadComponentHoook to get the design.
Conclusion:
Using Choook ClassUsereloadComponent`, you can safely recharge the only component when the active chain changes IT-Tag, causing causing. This solution must be integrated integrative response and provide a betrayal of a meeting with the number of telot in a single monitoring list.