Lets assume I have a React component (functional component) and i am passing multiple props. One of these props is a nested object like...
Example nested object
const user = {
id: 101,
email: '[email protected]',
personalInfo: {
name: 'Jack',
address: {
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}
}
}
For simplicity I want to pass the whole object, but instead of accessing it via user.personalInfo.adress.line1 I would like to save this to variable.
I am passing it to the following component...
Example React Component
const ExampleComponent = (props) => {
// Example 1
const [state1, setState1] = useState();
useEffect(() => {
setState1(user.personalInfo.adress.line1);
})
// Example 2
const state1Var = user.personalInfo.adress.line1
}
I know that saving props to states is a bad practice. (= Example1) So whats the smartest way to do that? Saving it to a class variable? (= Example2)
CodePudding user response:
There's nothing wrong with passing complex objects as props. Why do you need to save it to state? Just destructure the object in the child component (assuming it is not possibly null or undefined). React functional components are just functions, you don't need to save something to state in order to use it. Since you're passing it as a prop from a parent component, presumably the parent component keeps track of its state; when the parent state updates, the prop will change and your child component will rerender (or, in other words, your child component's function will be called with the new prop value(s)).
const ExampleComponent = (props) => {
const {personalInfo} = props.user;
/* ... */
}
CodePudding user response:
You do not need a state for this. You can simply destructure the object on render of components.
Note: using useEffect
without dependency variable, will retrigger the callback function on each render. It will be a memory issue useEffect(() => {},[])
.
const user = {
id: 101,
email: "[email protected]",
personalInfo: {
name: "Jack",
address: {
line1: "westwish st",
line2: "washmasher",
city: "wallas",
state: "WX",
},
},
};
const ExampleComponent = ({ user = {} }) => {
const { personalInfo = {} } = user;
const { name = "somedefault name", address = {} } = personalInfo;
return (
<div>
{name}
<br />
{address.line1}
<br />
{address.line2}
</div>
);
};