Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a prop value inside functional component can cause problems in react component?

If I receive a prop and change it in my functional component, can it create a problem? Or it's ok to change it inside the component?

e.g

const MyComponent = ({ foo }) => {

    // is this bad?
    foo = someCondition ? bar : foo

    return (...)
}

I know that I could create another variable and store the values, but I would like to know if changing the prop it self won't cause any problem because it's a functional component.

like image 417
Vencovsky Avatar asked Nov 29 '25 16:11

Vencovsky


2 Answers

No, it shouldn't create any problems. As with regular functions the arguments passed are their own variables in the function scope and don't mutate the original value passed to the function.

function something(value) {
  value = 'nothing';
}

var anything = 0;
something(anything);

// Anything should still be 0;
console.log(anything);
But I would suggest to not mutate your variables.
like image 53
Emiel Zuurbier Avatar answered Dec 02 '25 06:12

Emiel Zuurbier


If foo in your example is passed from the parrent, and the parrent keeps it in its state, then you would also need to pass setFoo as a paramater to your component and use that to update it properly.

function Parrent(){  
  let [foo, setFoo] = useState('foo');  
  return <Child foo={foo} setFoo={setFoo}/>
}

As for changing the props directly, you can if they are arrays or objects.

like image 42
Robert Andrei Avatar answered Dec 02 '25 04:12

Robert Andrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!