Skip to content

Bug: Strange double invocation of hook's setState in strict mode #23081

Closed
@Zombobot1

Description

@Zombobot1

React version: 17.0.2

Steps To Reproduce

  1. ???
  2. Invoke set state in the strict mode

Unfortunately, I cannot provide a small reproducible example of my issue. It occurs randomly in some specific component hierarchies. I can provide the problematical code and investigate this issue further if I get at least some hints why it may happen.

This is a simplification of my code:

// in parent component
const [arr, setArr] = useState([])

const appendData = useCallback((data) => {
	console.log('appending')
	setArr((old) => {
		console.log('setting state')
		return [...old, data]
	})
}, [])

// somewhere in children
<button onClick={() => appendData(2)}>Btn</button>

The current behavior

React appends the data twice, however, there is only one 'setting state' printed. I detect second invocation via debugger. The console.log('appending') is printed once.

The expected behavior

'setting state' is printed twice. I may assume that I'm doing something wrong, but I cannot find any explanation why on the second invocation nothing gets printed in console.
I expect that on both invocations the old state is equal. However, it seems like the second invocation gets updated state from the first one.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions