I've recently come across the following code:
import React, { useContext } from "react";
import ReactDOM from "react-dom";
import UserContext from 'UserContext';
const useUserName = () => {
const context = useContext(UserContext);
return context.userName;
}
function App() {
return (
<div className="App">
{useUserName()}
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
useUserName returns user name as a string. It seems instinctively strange and wrong that react hook useUserName is used inside JSX that is inside the "render" function. Is this valid usage? I couldn't find any reference which forbids such usage.
It seems instinctively strange and wrong that react hook useUserName is used inside JSX that is inside the "render" function.
The entire component is nothing but a render() function.
Is this valid usage?
What's the difference between that and
function App() {
const userName = useUserName();
return (
<div className="App">
{userName}
</div>
);
}
Technically this is valid and will work.
That said, I would suggest not to do it since someone can wrap this JSX with a conditional rendering and not noticing you are using a hook. Then it will be like calling it inside a condition. lets say someone add a code that is something like that:
return (
isLoading ? <Spinner/> : (
<div className="App">
{useUserName()}
</div>
)
);
And that is forbidden. The legacy docs of React explains why properly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With