zahraei
zahraei

Reputation: 79

difference between state separately and together in react js

I write state In the form of

 const [state,setState] =useState({
    type:false,
    imageSrc:'',
    captionImage:'',
    showImage:false,
});

when change state in the form of

setState({type:true});
setState({captionImage:'hellooo'});
setState({imageSrc:link});

and send it to another component, there is undefined in that component, but I write state In the form of

const [type, setType] = useState(false);
const [imageSrc, setImageSrc] = useState('');
const [captionImage, setCaptionImage] = useState(false);
const [showImage, setShowImage] = useState(false);

when change state in the form of

setType(true);

and send it to another component, there is ok in that component.

Upvotes: 0

Views: 43

Answers (1)

marcos
marcos

Reputation: 4510

Because in the first form, when you are setting the new state instead of passing a new full object like this:

{
    type:false,
    imageSrc:'',
    captionImage:'',
    showImage:false,
}

You are setting your state to this:

{type:true}

The other props are gone, if you want to replace only one prop in your state (for example type, while keeping the other ones, you would do something like this:

setState({ ...state, type: 'new value' })

Upvotes: 3

Related Questions