Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can react hooks be used inside JSX?

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.

like image 352
hitchhiker Avatar asked Jun 28 '26 05:06

hitchhiker


2 Answers

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>
  );
}
like image 92
Thomas Avatar answered Jun 29 '26 19:06

Thomas


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

like image 30
Sean Meir Avatar answered Jun 29 '26 17:06

Sean Meir