I am new to React (just 1 online course) and am discovering the magic of props and state. I realise that props are immutable and state is mutable. I am getting clearer about their uses but there's one point I would like to clarify that I have not been able to find online.
So props can be passed from Parent to Child and when they are passed the name of the variable holding the props can be changed. When state or its values are passed to child components, a mechanism is also passed along to the child to be able to modify the state at the parent level by the child.
I hope this is correct as so far this is what I have understood about props and state.
Now I have a project where I have "App.js" which is the topmost parent with "Home.js" as its child. I plan to use state
in both of them. But the state
in App.js is something of a global state (and I don't want to use redux) and the state
in Home.js would be the state that the application would use for its regular use.
Now both of them are being named using the state={}
format (I am using class based components) and referred to as this.state
but within their own components, which is working fine.
My question is about the format of naming state as state
, is this mandatory or just a standard that developers are expected to follow?
I've tried to change the name of the state and it seemed to work but maybe I did something wrong as I didn't really expect it to work... so that's why I wanted to confirm if it's ok to change the name of state in a component to something like globalState
or store
Any advise would be appreciated.
CodePudding user response:
When writing Class Components, you can only update the state using the setState
method and it will write the state to the state
property.
While I suppose you could add a globalState
getter property to the class which returns the value of state
, this seems pointless.
Note that storing data in other properties instead of using setState
to write to it will not trigger a re-render. You're just writing to a property on the object and not dealing in anything that React considers state.
When writing Function Components, state is handled with the useState
hook and the processing of storing the state data is handled by React internals. The state value is then assigned to whatever variable you want to assign it to after reading the returned state array.
const [anyName, setAnyName] = useState(defaultValue);
const [anyOtherName, setAnyOtherName] = useState(otherDefaultValue);