Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In reactjs, are props pass by value or pass by reference?

Tags:

reactjs

As far as I can tell, if I pass a parent component state down to a child, then that child gets the live state of the parent.

So a change made in the state of the parent is immediately also available in the child via the prop that it came on.

Is this correct?

like image 387
Duke Dougal Avatar asked Jun 26 '16 10:06

Duke Dougal


People also ask

How are props passed in React?

export default App; Basically that's how props are passed from component to component in React. As you may have noticed, props are only passed from top to bottom in React application's component hierarchy. There is no way to pass props up to a parent component from a child component.

Can you pass objects as props in React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.

What is true about props in React?

“Props” is a special keyword in React, which stands for properties and is being used for passing data from one component to another. Furthermore, props data is read-only, which means that data coming from the parent should not be changed by child components.


1 Answers

It's basically the same mechanism as anywhere else in the language, as you'd expect. Primitives are passed by value and variables that aren't primitives will be passed by reference.

React takes care internally of the updating of props, so that children always have the most up-to-date value of the prop.

This is the lifecycle method that is called when receiving new values for props.

However, make sure you respect the infrastructure put in place and the exposed API that React gives you.

like image 185
Elod Szopos Avatar answered Oct 12 '22 02:10

Elod Szopos