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

Time:12-03

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

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?

CodePudding user response:

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

  • Related