Bug: updating array in state updates other states too

This issue has been created since 2022-11-10.

React version: 18.2.0

Creating multiple useState hooks with the same initial data, and then updating an array in just one of them updates the other ones as well.

Steps To Reproduce

  1. Create two states with the same data (and make one property an array)
  2. Update the array property in just one of them

Link to code example: https://codesandbox.io/s/react-multiple-state-xhz9wu

The current behavior

Both states update

The expected behavior

Only the updated state updates

frostzt wrote this answer on 2022-11-10

EDIT: I think I too got it wrong, as @sacru2red mentioned. Thanks for the explanation.

sacru2red wrote this answer on 2022-11-10

It's bug?
I Think just human error to set init state..
https://codesandbox.io/s/react-multiple-state-forked-2ldliq?file=/src/App.js

hasanbisha wrote this answer on 2022-11-10

there is mutation in this example, it is not a bug for my opinion

Tasztalos69 wrote this answer on 2022-11-14

@sacru2red originally I populated the state with a useEffect, the initial state is just for showcase.

If it is indeed intended behavior, could someone explain why? It seems illogical to me that both states update, and (maybe I missed something) but I couldn't find anything about why shouldn't I do what is in the example.

rupakhetibinit wrote this answer on 2022-11-14

@Tasztalos69

const initialArray = ['hello','hi','bye'] // some array

const copiedArray = initialArray; // this doesn't copy the array but gets a reference to the initialArray also
// called shallow copy

copiedArray[0] = "nope" // mutate the copied array

console.log(initialArray===copiedArray) // logs true in console even though initialArray is declared above copiedArray 
// they both references same values and both are mutated whenever you mutate 1
const initialArray= ['hello','hi','bye']

const deepCopiedArray = [...initialArray]; // if there were multiple nested fields you need to copy the array
// going upto that nesting level [...something,[...otherthing]]
deepCopiedArray[0] = "nope" // mutate the state array

console.log(initialArray===deepCopiedArray) // logs false because both of the array are referencing separate values

You need to perform deep copy whenever you're working with react. I created an updated CodeSandbox from your code here

Tasztalos69 wrote this answer on 2022-11-14

I see @rupakhetibinit , thanks.

More Details About Repo
Owner Name facebook
Repo Name react
Full Name facebook/react
Language JavaScript
Created Date 2013-05-24
Updated Date 2022-12-10
Star Count 198882
Watcher Count 6638
Fork Count 41302
Issue Count 1120

YOU MAY BE INTERESTED

Issue Title Created Date Comment Count Updated Date
Allow more characters in quoted field names. 2 2022-11-29 2022-12-03
Issue with tokenizer 1 2022-11-24 2022-11-23
[Question][Integration] Will MS365 and TestLink / Kiwi be supported? 1 2022-09-30 2022-10-10
Canu crashes after beginning assembly with message "Overlap error adjustment jobs failed, tried 2 times, giving up" 2 2021-11-12 2022-11-30
using PISM with Newtonian fluids 1 2022-03-27 2022-12-01
OpenMPI problem: PISM ERROR: Ice thickness exceeds the height of the computational box 2 2022-03-15 2022-11-27
Don't allow TreeParts inside generics 1 2021-09-05 2022-11-16
Incorrect rendering of planet's circle in-flight on real hardware 0 2021-07-02 2022-11-14
[Feature request] Adjustable buffer time 2 2022-09-29 2022-12-01
[Feature Request] Manually choose tracklist's album name fields 2 2022-09-21 2022-12-01
RGUtility.ParseTabbedString throws System.IndexOutOfRangeException with empty string argument 0 2021-09-01 2022-11-13
arm64 support 5 2021-03-05 2022-01-01
is it possible to define dependency for CHECKs 1 2021-11-01 2022-10-08
Improved Call Notifications 1 2021-11-25 2022-09-30
cisco.nxos.nxos_vlans in v2.7.0 breaks on older platforms: show vlan | json-pretty breaks 'older' code versions 2 2021-10-21 2022-11-17
Area line chart string vs int index issue 1 2019-10-17 2022-07-02
problems installing spearmint and testing the simple example 7 2017-08-09 2022-11-25
Convert Word Document to PDF: Font is missing in PDF 1 2021-05-04 2022-11-29
How to pushAndRemoveUntil to a screen without showing NavBar 2 2022-04-01 2022-11-25
Make `function not found` a deterministic failure 14 2021-12-13 2022-11-21
'tuareg-eval-phrase' no longer works as before 13 2021-06-07 2022-11-25
Replace minimal cohort_data_phenos.csv with one with the complete list of phenotypes in CB 0 2021-01-15 2022-11-18
pitest-survival-check-xml.groovy: ArrayIndexOutOfBoundsException 1 2022-08-28 2022-09-18
Spring Data fails with "IllegalArgumentException: Not a managed type" - Maven & Java version 1 2022-08-10 2022-11-26
Track 'Upsell Funnel Engine' 0 2022-03-22 2022-11-08
Track 'jQuery Modal' 0 2022-03-23 2022-11-17
Feature not working 2 2021-10-17 2021-12-26
Missing TypeScript declaration for formatter 4 2021-10-15 2022-07-09
ftp access failure 0 2021-05-14 2022-01-05
Extend occ (tags) with commands to add and remove tags to/from files 0 2022-06-06 2022-10-22
Allow specification of file encoding 0 2014-07-23 2022-07-27
Is this project abandoned? 0 2022-11-17 2022-12-03
[Success Image Report]: Parrot Sec 5.0.1 1 2022-06-07 2022-12-04
0-[MQTTCoreDataPersistence allFlowsforClientId:incomingFlag:]_block_invoke 0 2020-09-11 2022-11-27
Bug after updating mac 4 2022-09-14 2022-11-30
how to add google pay feature in initPaymentSheet useStripe() 1 2022-09-14 2022-11-30
add CUDA file extensions to cpp language-map 0 2019-05-28 2022-11-19
failed to run, because of version conflict 4 2021-08-23 2022-11-30
Sentinel Lab - Module 5 - No HighRiskApps Watchlist 4 2022-02-14 2022-12-06
Nested describes - separate test suites 9 2020-06-21 2022-11-26
[request]: Rust API Reference Guide 2 2021-11-05 2022-09-28
[CoE Starter Kit - BUG] Sync flow errors mail coming in malformatted 2 2021-09-23 2022-10-28
Feature: Notification before event ending 2 2021-04-18 2022-02-04
[loss OVERFLOW] Several Issues 2 2021-11-29 2022-09-15
Copy Schema to Clipboard does not work on Safari 0 2022-03-17 2022-12-03
同时使用真实接口及Mock 0 2022-01-07 2022-01-16
在arm64-v8a上public native int getLogLevel(long logInstancePtr);总是返回6 0 2021-05-21 2022-12-04
[Bug] y坐标轴位置不对 3 2022-01-14 2022-01-23
Android使用 logupload 上载文件,一直显示失败 3 2020-11-09 2022-11-06
React 18 - HeadlessUI dialog and transitions stopped working 2 2021-12-21 2022-10-24