Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it bad to use props value on react hook?

I'm new in react hooks and I just don't see this on docs:

const MyComponent = ({myProp}) => {
 const [myPropHook, setPropHook] = useState(myProp)
...
}

I'm wondering if this is a good practice?

like image 769
gpbaculio Avatar asked Dec 13 '22 11:12

gpbaculio


1 Answers

The value you pass to useState is used as a starting value for the state variable. So, when your component props change, they will not affect the state variable you are using. The initial value would be the first props sent to the component and after that can be modified only using the setPropHook function.

So, in short, it is definitely a code smell to use props as initializers for useState because reading the code does not correctly convey what will actually happen.

like image 125
Arsalan Ahmad Avatar answered Dec 25 '22 06:12

Arsalan Ahmad