Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference in react between rendering component and calling a function which returns JSX

Can somebody help me figure out what is going on here and why? I’ve tried googling, but people focus on one way being faster vs other, one being more correct, etc… I didn’t find resource which explains what is going on under the hood, what is the actual implementation difference and why do they behave differently.

I am interested in why it behaves like it does and what triggers that behavior.

Let’s look at this code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const SomeComponent = (arg) => {
  const [typedAnswer, setTypedAnswer] = useState();
  const shouldAskForUserInput= arg === 1; // assume true
  const handleInputChange = (e) => setTypedAnswer(e.target.value);

  const ShortAnswer = () => (
    <Input type="text"
           name="answer"
           value={typedAnswer}
           autofocus
           handleInputChange={handleInputChange} />
  );

  return (
    <div>
      <p>whatever</p>
      <p>something else</p>
      {shouldAskForUserInput && <ShortAnswer />}
    </div>
  )

In this example, it will render a div with 2 p and an input field. This input field, when typed into behaves like any normal controlled component, except it doesn’t.

If you type test into this input field and then move your cursor in the middle and try typing numbers 12 you will end up with string te1st2. This is because after each keypress (onChange) it will render again the input field. If I remove autofocus from input, you can type only one character at the time.

If I change following so that it is function call instead

  return (
    <div>
      <p>whatever</p>
      <p>something else</p>
      {shouldAskForUserInput && ShortAnswer()}
    </div>
  )

It will start to behave as expected, I can type any number of characters inside the input, it doesn’t rerender on change, etc. Same result if I remove the function all together and put the input code directly instead of function call.

Now, what is actually happening there and why?

>Solution :

Here you go! The article doesn’t go into React.createComponent() as much but I think it’s a good jumping-off point.

https://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l

https://reactjs.org/docs/react-without-jsx.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading