In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the ways to simplify React Hook". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the ways to simplify React Hook"?
1. Reduce the number of useState
When you use hook for development, it's easy to use too many useState calls or reduce all states to a single, overly complex useState. One of the best ways to improve the readability of hook is to give priority to your useState calls. I like to follow some rules about state implementation in the hooks I write.
(1) priority is given to readability
I prefer to read the state as an object rather than using multiple useState commands with simple values. Using fewer useState commands will also make the return of your hook easier and the implementation in the component more straightforward. Although this is my preference, code is a very personal thing and very expressive. My first rule when writing code is to give priority to readability. Following this rule will make your code easier to maintain, force you to think about what you write, and make it easier for others to follow your code. If this is the only thing you take from this article, then I have finished my work.
(2) evaluate the content of the status object
Components are not perfectly planned from the beginning, and as components grow, the properties contained in your useState may become more and more complex. Throughout the development cycle, I strongly recommend that you evaluate the content of your useState calls to determine whether it makes sense to divide the state part into other useState calls. You may want to group status values by function or type. In general, I like to group state data by attributes that I think are usually updated together, or by the functions of state properties, such as data and view properties.
two。 Use your Hook return
When I first started writing custom Hook, it was easy to follow a return style similar to the default useState hook. While this is not a bad thing, it can be troublesome to use a return array on top of a function to return multiple state variables. Imagine that in addition to the functions that deal with data selection, you can return hooks for two different state variables (one is data state and the other is view state), written in an array-style return way, which might look like this.
Function useBasicHook () {const [dataState, setDataState] = useState ({serverData: {}, selections: {}); const [viewState, setViewState] = useState ({menuExpanded: false, submitFormData: {}}) const toggleMenuExpand = () = > {setViewState ({menuExpanded:! viewState.menuExpanded, submitFormData: viewState.submitFormData})} return [dataState, viewState, toggleMenuExpande] } function BasicComponent () {const [dataState, viewState, toggleMenuExpand] = useBasicHook (); return}
If you look at this hook, it's easy to see that if you add additional functions or variables to the return, the implementation of hook can quickly get out of control. If you accidentally break the order of the array, or use an incorrect name, it will cause additional confusion and possible errors. We can prevent this from happening by updating the hook to return an object, like this.
Function useBasicHook () {const [dataState, setDataState] = useState ({serverData: {}, selections: {}}); const [viewState, setViewState] = useState ({menuExpanded: false, submitFormData: {}}) const toggleMenuExpand = () = > {setViewState ({menuExpanded:! viewState.menuExpanded, submitFormData: viewState.submitFormData}) return {dataState: dataState, viewState: viewState, toggleMenuExpand: toggleMenuExpand} } function BasicComponent () {const state = useBasicHook (); / / or / / const {dataState, viewState, toggleMenuExpand} = useBasicHook (); return}
Converting the return value to an object has other benefits, including:
If hook is shared between multiple components or as a library, the compatibility of the hook version is improved after the update
When using Hook to provide the same level of Hook API at the top of the component, you can still deconstruct the object.
Another cool thing you can return with your hooks is to create small states in your state based on component factory functions. This provides a good way to share the component builder with the component that implements the hook without exposing state to the component.
3. Simplify setState calls using merge hooks
Using classes instead of function-based components for development in React does have some out-of-the-box advantages when it comes to state management. For me, the most important thing is to merge the old state with the new state. React Docs for State provides a good example of the stateful merging feature built into React.Component. Although this feature is not built directly into the hook, we can replicate this behavior through a simple custom hook that replaces our useState call and gives us the same behavior.
Function useMergeState (initialState) {const [state, setState] = useState (initialState); / / use useRef to improve the functionality of asynchronous calls to setState. Const stateRef = useRef (state); function setRefState (newState) {stateRef.current = newState; return setState (newState);} function mergeState (newState) {var finalState = newState; / * determine whether the state data type matches, if so, continue merging, * if not, throw a console warning and overwrite with the new status. * / if (typeof stateRef.current! = = typeof newState) {console.warn ("useMergeState warning: the state data type does not match, overwrite the state with the new state." ); finalState = newState } else {/ * merge * / if (typeof stateRef.current = = "object" & &! Array.isArray (stateRef.current)) {/ / the existing state is an object Continue trying to merge if (typeof newState = = "object" & &! Array.isArray (newState)) {finalState = {... stateRef.current,... newState} } return setRefState (finalState);} return [stateRef.current, mergeState];}
4. Consider splitting Hook
Regardless of the complexity of the component, I always recommend using custom hooks; however, when building custom hooks, it is useful to split an overly complex hook into several simpler hooks. In my project, I like to split hook logic by function, for example, it might be beneficial to split a hook into a logical subset of states, such as a hook for data / Web API interaction and a separate hook for displaying state. Recall the example hook in the return part of the hook, which might be helpful to take it apart.
Function useDataHook () {const [dataState, setDataState] = useState ({serverData: {}, selections: {}}); return dataState } function useDisplayHook () {const [viewState, setViewState] = useState ({menuExpanded: false, submitFormData: {}}) const toggleMenuExpand = () = > {setViewState ({menuExpanded:! viewState.menuExpanded, submitFormData: viewState.submitFormData})} return {viewState: viewState, toggleMenuExpand: toggleMenuExpand} function BasicComponent () {const data = useDataHook (); const display = useDisplayHook (); return}
Sample hook after split
5. Evaluate useEffect calls to prevent unnecessary re-rendering
UseEffect hooks are very useful, but can lead to overrendering if they are not used properly. When viewing custom hooks, it's worth evaluating your useEffect calls. I like to follow the following rules of thumb:
If an useEffect listens for state variables in the same hook scope, then this effect should not update the state itself.
If you have multiple useEffect statements listening on the same set of variables, consider grouping them together.
Although using useEffects in conjunction with useEffects can help reduce the number of re-renderings, the readability of the code is a priority.
Thank you for your reading, the above is the content of "what are the methods of simplifying React Hook". After the study of this article, I believe you have a deeper understanding of what the method of simplifying React Hook has, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.