Home > Software engineering >  Why do we need a `props` parameter in React?
Why do we need a `props` parameter in React?

Time:08-02

I still don't get why we need a prop(s) in react, seriously. Why can't we just declare everything we need as an argument or parameter in the child component, then declare it, why do we have to declare it in a parent element then pass the props to the child component then catch it. I don't understand why. It seems a bit confusing, I'm yet to see the why in it

CodePudding user response:

Props are useful in the case that you have a controller in the parent component and you want to pass the value of that controller to the child to make a certain action. The replacement for props would be to store everything globally in redux or mobx, but that needs much work. for example

const ParentComponent = () =>{
    const [flag, setFlag] = useState(false)
    return(
          <div>
               <button onClick={()=>setFlag(!flag)}>click me!</button>
               <ChildComponent flagValue={flag}/>
          </div>
)

}

as in the example for some reason the button that changes the flag is in the parent and you need to use that value in the ChildComponent. So here you benefit a lot from using props.

Also in writing a cleaner code and drier one so as not to repeat the same values in different react components

CodePudding user response:

You might not be familiar with React if you ask such questions (no anger at all). It's one of the main concepts of the React library.

You can easily split a huge component into smaller pieces. But then, you need to provide the same data here and there. To prevent repeating yourself (DRY - don't repeat yourself), you can share the prop with many child components.

If you are interested in React - check the documentation. It's one of the prettiest documentation I've ever read.

CodePudding user response:

prop changes trigger UI re-render for the child component. That's one of the props of using props.

CodePudding user response:

You can declare a prop in a child component, but you won't have reactivity on it.

  • Related