In my React application I have the next situation. 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. I know that my question is more theoretical, but what is better in my case:
To add this logic on each page; or
To create a custom hook like useButtonMessage()
which will look like this:
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?
Personally, I like to create hooks with all relative things of a particular topic (instead of just one constant like 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
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
},
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.