简体   繁体   English

React hooks 性能和最佳实践

[英]React hooks performance and best practices

In my React application I have the next situation.在我的 React 应用程序中,我遇到了下一种情况。 On each page I have to create this logic:在每个页面上,我都必须创建这个逻辑:

const user = useUser();
const message = user.auth ? 'Welcome' : 'You are not allowed'
    

<Button>{message}</Button>

I have to add this logic on 10 pages.我必须在 10 页上添加这个逻辑。 I know that my question is more theoretical, but what is better in my case:我知道我的问题更具理论性,但在我的情况下更好的是:

  1. To add this logic on each page;在每个页面上添加此逻辑; or或者

  2. To create a custom hook like useButtonMessage() which will look like this:创建一个像useButtonMessage()这样的自定义钩子,如下所示:

     export const useButtonMessage = () => { const user = useUser(); const message = user.auth ? 'Welcome' : 'You are not allowed' return message; }

Won't the hook be redundant if it keeps only 3 lines of code?如果只保留 3 行代码,钩子会不会是多余的?

Personally, I like to create hooks with all relative things of a particular topic (instead of just one constant like message ).就个人而言,我喜欢使用特定主题的所有相关事物创建挂钩(而不是像message这样的常量)。 For example:例如:

 export const useAuth = () => {
   const user = useUser()

   const isLoggedIn = user.auth
   const welcomeMessage = isLoggedIn ? 'Welcome' : 'You are not allowed'

   /*
     add selectors, functions to dispatch actions, 
     or other util contants such as welcomeMessage
   */

   return {
     isLoggedIn, // use this constant across your app to check if the user is logged in
     user, // use this across your app to obtain the user
     welcomeMessage,
   };
 }

I wouldn't create a hook for that but rather create a messages file where all the messages of the app will be stored我不会为此创建一个挂钩,而是创建一个消息文件,其中将存储应用程序的所有消息

And then you can add conditional properties fe然后你可以添加条件属性 fe

export const messages = 
{
 userAllowed: (authenticated: boolean) => authenticated ? 'welcome' : 'you are not allowed'
}

You can even take it a step further:你甚至可以更进一步:

export const messages =
{
 Welcome: 'welcome',
 NotAllowed: 'you are not allowed',
 userAllowed: function(authenticated: boolean) { 
  return authenticated ? this.Welcome : this.NotAllowed
 },
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM