This article is a follow-up to this article about how to avoid rendering the React component repeatedly. If you haven’t read the first article, I recommend you do!!

If you find this article helpful to you, please don’t be stingy with your like πŸ‘ oh! Your approval is the biggest motivation for me to keep writing! Thank you very much!

🀟 other uses of useRef

If you have a situation where you want to save the last previousValue of your input, how do you do that? You might write something like this:

// Save the previously entered inputValue // Save the previously entered inputValue let pervValue: string = ""; const UseRefOpt = () => { const [inputValue, setInputValue] = useState<string>("hello"); const handelInputChange = (e: ChangeEvent<HTMLInputElement>) => { setInputValue((oldValue: string) => { pervValue = oldValue; return e.target.value; }); }; UseEffect (() => {console.log("πŸš€ inputValue:", inputValue, "πŸš€ pervValue:", pervValue); }, [inputValue]); Return (<div> {/* <h1>UseRef multifunctional use</h1> */} <h1> <input type="text" value={inputValue} onChange={handelInputChange} /> </div> ); };Copy the code

OK, so that would solve the problem, but do you see a problem? When the component is unloaded and reloaded, is pervValue still the original empty string?

View a preview:

Then you might say: why don’t I just reinitialize when I uninstall? For example:

UseEffect (() => {console.log("πŸš€ inputValue:", inputValue, "πŸš€ pervValue:", pervValue); return () => { pervValue = ""; }; }, [inputValue]);Copy the code

Ok, no problem! What if this component is used more than once? Is this notation still supported?

πŸ“£ When this component is used multiple times, it will only have a name in memory calledpervValueThe value of all components will be saved to this variable, will cause the saved value is not accurate!

So this is not the right way to write it. So how do you write that? Use useState? , don’t!!!!! Such unnecessary values do not need to be declared as states, causing repeated rendering of the page. So in this case we can use useRef. So why use it?

  • Changing the current property of the πŸ‘ useRef return value does not cause the component to be rerendered.
  • πŸ‘ When a component is uninstalled, there is no need to reinitialize the value of useRef.
  • πŸ‘ Because the return value of useRef is an object, we use it in the same way we use this for the class component.

Such as:

const UseRefOpt2 = () => { const [inputValue, setInputValue] = useState<string>("hello"); const pervValueRef = useRef<string>(""); const handelInputChange = (e: ChangeEvent<HTMLInputElement>) => { setInputValue((oldValue: string) => { pervValueRef.current = oldValue; return e.target.value; }); }; UseEffect (() => {console.log("πŸš€ inputValue:", inputValue, "πŸš€ pervValueRef:", pervValueRef); }, [inputValue, pervValueRef]); Return (<div> {/* <h1>UseRef multifunctional use</h1> */} <h1> <input type="text" value={inputValue} onChange={handelInputChange} /> </div> ); };Copy the code

This completes the requirement.

View a preview:

🀟 Context provider optimization

React state management packages are currently available in the community. However, for some small projects, it is undoubtedly not worthwhile to download a status management package and use it only a few times. Therefore, many people choose the Context API + useReducer to manage the state of the project!

However, with the increasing number of project states and the separation of concerns, it is not clear whether there is a provider in your project.

const ProvidersOpt = () => { return ( <Context5.Provider value="Context5"> <Context4.Provider value="Context4"> <Context3.Provider value="Context3"> <Context2.Provider value="Context2"> <Context1.Provider value="Context1"> <div> {/* <h1>Providers Optimization</h1> */} <h1>Providers Optimization</h1> </div> </Context3.Provider> </Context4.Provider> </Context5.Provider> ); };Copy the code

Isn’t this a hell of a callback at a glance?

So wouldn’t it be better if we could level the Providers?

So we can write a method that does this! For example, see Redux

// πŸ“£ value is a combination of my examples, so you can write it according to your own situation!! function providerOpt(... providers: React.Provider<string>[]) { return ({ children, value }: { children: JSX.Element; value: string[] }) => providers.reduce( (prev, Provider, index) => ( <Provider value={value[index]}>{prev}</Provider> ), children ); }Copy the code

So how do you use it?

const OptProvider = providerOpt( Context1.Provider, Context2.Provider, Context3.Provider, Context4.Provider, Context5.Provider ); const ProvidersOpt2 = () => { return ( <OptProvider value={["Context1", "Context2", "Context3", "Context4", } > {/* <h1>Providers Optimization</h1> </OptProvider>); };Copy the code

This writing method mainly uses the characteristics of Reduce to add children to the new Provider. The final rendering effect is the same as the previous writing method of hell callback, but we can not see the hell callback in the visual.

πŸ‘‡πŸ» Click to view the source code.

πŸ‘πŸ‘πŸ‘ past wonderful

  • πŸ‘ Do you know how to avoid repeat rendering of the React component?
  • πŸ‘ project to introduce ESBuild, compile directly to heaven!!
  • πŸ‘ Best practices for using WebComponents in React
  • πŸ‘ How can I optimize the 50+MB APP package to 4.2MB?
  • Can you explain the principle of πŸ‘ Styleds – Components?
  • πŸ‘ Interviewer: Can you talk about the difference between extends and a parasitic composite inheritance stereotype?
  • πŸ‘ Front-end Leader asked me to talk to my colleagues about event loops
  • πŸ‘React compares status updates with Vue
  • πŸ‘ How do I React to a tree shuttle box?
  • πŸ‘ 10 Mistakes to avoid when using React
  • πŸ‘ Webpack Packaging Optimization Direction Guide (Theory)
  • πŸ‘ Vue encountered drag and drop dynamically generated components?
  • πŸ‘JS Coding tips, most people can’t!!
  • πŸ‘TypeScript Doesn’t it smell? Come on!