What is the different between react component and function as component in react

Viewed 73

I'm very confused learning react. For example I have very simple react component

export default function Foo(){
    return(
        <div>
            <div>some text</div>
        </div>
    )
}

And I want to add a child component:

export default function Foo(){

    const Bar  = ()=>{
        return (
            <input placeholder="some input"/>
        )
    }
    return(
        <div>
            <div>some text</div>
        </div>
    )
}

And as much as I know, I can use this component in two ways:

1. Use as function

return(
        <div>
            <div>some text</div>
            {Bar()}
        </div>
    )

2. use as component:

 return(
        <div>
            <div>some text</div>
            <Bar/>
        </div>
    )

What exactly different between these two? I thought it was same, until I faced an issue with input field, that if I use component as <Bar/>, The focus on input field will be lost after I enter first letter

Demo here: https://codesandbox.io/s/gifted-archimedes-l7bce7?file=/src/App.js

So what is the exact problem here? I code as component all the time, as per my understand <Bar/> is same as Bar() when it return react component

Am I right or not?

Edit: I found this blog, and it very close to this question and it great too :) https://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l?signin=true

3 Answers

I have seen your codesand box demo, form there I think that the reason for losing focus from input field is the place where you have used useState.

Your can do two things here that's:

Either

  1. Pass the state as props from parent to child component.

Or

  1. use useState inside your child component as the parent does not require the state value I prefer the second way.

You can Read this for more knowledge of where to put the useState and when do you really need to use useState.

  1. To be a component, function returning JSX should be used as <Component /> and not as Component().

  2. When a functional component is used as <Component /> it will have a lifecycle and can have a state.

  3. When a function is called directly as Component() it will just run and (probably) return something. No lifecycle, no hooks, none of the React magic.

The above 3 statement is the answer to your probem.

When you call the component as {Child()}, it does not have any lifecycle or hook and when you call as , it has it's own lifecycle and hooks this is why you are facing those problems.

For more read on this topis: Link.

When you create a new component you can re-use that in another functional component.Whereas, If you create function then you cannot re-use in another functional component, it will have limited access to that particular functional component only.

Related