Solvedreact easy state batching eventlistener breaks input editing with React 16.9

Hello,

We've upgraded to React 16.9 (from 16.8) and it breaks our controlled inputs because of something inside react-easy-state. It is fixed as soon as I remove the batching of eventlisteners here: https://github.com/solkimicreb/react-easy-state/blob/1aeb0ddbc386a36adc3758a12d740989e99655a6/src/scheduler.js#L87

What breaks?

  • Write "Hello world" in an input
  • Edit the input: Put your cursor right before "world", and try to add "dear".

Expected result: "Hello dear world".
Actual result: "Hello dworldear"

The cursor moves to the end of the input everytime you add a character.

Here's how to recreate:

import React, { Component } from 'react';
import { view } from 'react-easy-state';

class Input extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: '',
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({ value: e.target.value })
  }

  render() {
    return <input type="text" value={this.state.value} onChange={this.handleChange} />
  }
}

export default Input;

OR, with hooks:

import React, { useState } from 'react';
import { view } from 'react-easy-state';

function Input() {
  const [value, setValue] = useState('');

  function handleChange(e) {
    setValue(e.target.value);
  }

  return <input type="text" value={value} onChange={handleChange} />
}

export default Input;

Why is it related to react-easy-state?

  • Remove the line I mentioned above and it works
  • Remove the react-easy-state import and it works
  • Note that we're not even using react-easy-state, only importing it. Same result if you do wrap the component in view though.

We noticed a comment a few lines above // this should be removed when React's own batching is improved in the future, perhaps React 16.9 batching is improved now? 😄

Thanks for an otherwise great state management tool!

8 Answers

✔️Accepted Answer

Quite a critical bug imho. Repro at https://codesandbox.io/s/vigorous-grothendieck-63ybi.

Typing into the middle of <input> resets the cursors to the end. Is this module monkey-patching React given that the issue shows without wrapping a component in view? I would strongly suggest not doing that for forward compat cases like this.

Other Answers:

@solkimicreb I'd love to help with this but I'm going to need your help.

The first thing I wonder is if we can get rid of unstable_batchedUpdates altogether.

Is the monkey-patching of scheduler.js used to:

  • Solve the stale-props/zombie-children* problem? If it is not, how does react-easy-state solve it?
  • Batch mutations together (like the old mobx transaction)?
  • Any other reason?

* There's an excellent article of Kai Hao (@kevin940726) about the stale-props/zombie-children problem of state managers. Following that, Paul Henschel (@drcmda) introduced an alternative solution on Zustand based on an incremental id which may be interesting: pmndrs/zustand#65

The React dev team has released the documentation of React Concurrent. It states this about unsafe_batchedUpdates:

*: Legacy mode has automatic batching in React-managed events but it’s limited to one browser task. Non-React events must opt-in using unstable_batchedUpdates. In Blocking Mode and Concurrent Mode, all setStates are batched by default.

https://reactjs.org/docs/concurrent-mode-adoption.html#feature-comparison

I've done some tests and it works great. It looks like unsafe_batchedUpdates is not needed at all in Concurrent mode:

https://codesandbox.io/s/react-easy-state-batch-bug-v5yne

I had to do the tests in the DOM because the testing library of React has not been updated yet to support Concurrent mode.

It also works on the upcoming Blocking mode, which could be adopted as soon as Concurrent mode is released:

For older codebases, Concurrent Mode might be a step too far. This is why we also provide a new “Blocking Mode” in the experimental React builds. You can try it by substituting createRoot with createBlockingRoot. It only offers a small subset of the Concurrent Mode features, but it is closer to how React works today and can serve as a migration step.

I wonder how long would it take to the React team to release Concurrent mode in the stable version, tho.

So on the other hand, the way I was thinking to solve this is using an async scheduler. The library @nx-js/queue-util (by @solkimicreb as well) works fine.

This is the same codesandbox with tests but with React version 16.11. Without scheduler, but with the async scheduler fix. The<Input> component works fine again.

https://codesandbox.io/s/react-easy-state-batch-bug-async-scheduler-6q2dt

Miklos, what do you think? What is the advantage of monkey patching the native elements over using an async scheduler and why did you do that instead of this in the first place?

The package is moved to @risingstack/react-easy-state v6.2.0 of the new package includes the fix for this issue, please move to that package 🙂 There are no breaking changes.

Related Issues:

7
react easy state batching eventlistener breaks input editing with React 16.9
Quite a critical bug imho Repro at https://codesandbox.io/s/vigorous-grothendieck-63ybi Typing into ...
3
react easy state Performance question
Updated it for functional components: Hi So I’ve been using your library with preact and am quite am...
3831
axios Axios catch error returns javascript error not server response
I have exactly the same environment Try this: Modify from console.log(error) to console.log(error.re...
2346
jest Bug: Watch mode on Linux causes a ENOSPC Node.js error
From my findings its not related to Jest at all On Linux (or Mac) we have a max number of system wat...
1975
react RFClarification: why is setState asynchronous?
So here’s a few thoughts This is not a complete response by any means but maybe this is still more h...
1745
react Preventing rerenders with React.memo and useContext hook.
This is working as designed There is a longer discussion about this in #14110 if you're curious ...
1400
TypeScript Quick fix for 'unions can't be used in index signatures, use a mapped object type instead'
You can do this: Though Bar has no index signature (i.e. you can't then do (obj as Bar)[value as Foo...
811
webpack Cannot assign to read only property 'exports' of object '#<Object>' (mix require and export)
The code above is ok You can mix require and export You can't mix import and module.exports. ...
778
yarn Yarn Debian key expiry date updated (EXPKEYSIG 23E7166788B63E1E)
sudo apt-key adv --refresh-keys --keyserver keyserver.ubuntu.com also works to fix this issue for ma...
727
webpack How to exclude node_modules but one
@borm: a solution: Subj as example I create some module in another folder ( /projects/MY_MODULE ) MY...
720
yarn GPG error: https://dl.yarnpkg.com/debian stable InRelease NO_PUBKEY E074D16EB6FF4DE3
Doing curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add - again was enough. ...
611
react React Fire: Modernizing React DOM
I love every of these points except the className change For latest status see an update from June 5...
608
angular Angular5.x lazyLoad problem, undefined is not a function
For others that find this issue via Google as i did: I had the same problem when trying to lazy load...
595
react starter kit How to call child component method from parent?
For example you can use Refs to Components approach like so: Demo: https://jsfiddle.net/frenzzy/z9c4...
561
react How should we set up apps for HMR now that Fast Refresh replaces react-hot-loader?
Okay here goes What Is Fast Refresh? It's a reimplementation of hot reloading with full support from...
548
svgo no such file or directory .svgo.yml
I noticed this problem with Yarn after someone had run yarn clean Deleting the .yarnclean file delet...
521
ant motion 模版代码下载下来导入到dva搭建的项目里面,启动时报错(npm start)
开启 JavaScript 就可以了 你好,我下载的Home项目引入到项目工程里面,为了方便,我全部放到了components下面,引入和基本流程没有问题。在家里的win10上面启动没有报错,在win...
516
react native gesture handler Unsupported top level event type "onGestureHandlerStateChange" dispatched
Because my navigators were created asynchronously the handler was registered too late and thus throw...
506
electron Requiring electron outside of main.js causes a TypeError
For anyone encountering this problem in the future and reading this thread Electron version: 1.3.5 O...
499
babel ReferenceError regeneratorRuntime is not defined
I had this issue using rollup with babel I just used this babel config to resolve it : ...
488
webpack nodejs 17: digital envelope routines::unsupported
workaround: Bug report What is the current behavior? Other relevant information: webpack version: 5....
474
meteor [1.4.2.1] Error: ENFILE: file table overflow
I was getting the same after an upgrade to macOS Sierra Turns out macOS have a harsh limit on number...
473
webpack TypeError: Data must be a string or a buffer
Here is a workaround to help you to find the wrong import Using the latest 2.2.0 release although th...
429
vue router how to change document.title in vue-router?
Hi thanks for filling this issue You can simply define title in route's meta I really want set title...
425
babel eslint ESLint: 2.10.0 - Parsing error: Unexpected token =
parser: babel-eslint is OK! I'm using: and getting the following error: Parsing error: Unexpected to...
425
jest Error in Async Example: ReferenceError: regeneratorRuntime is not defined
This worked for me to fix ReferenceError: regeneratorRuntime is not defined in Jest: Then in .babelr...
417
jest babel-jest does not transpile import/export in node_modules when Babel 7 is used
For the record 🐛 Bug Report I started getting the dreaded SyntaxError: Unexpected token import erro...
413
react Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
You're exporting a React element not a component Change to Alternatively at the call site change <Co...
411
react Trigger simulated input value change for React 16 (after react-dom 15.6.0 updated)?
After some research of react source code I got a hack method for react 16: NOTICE: JUST A HACK ...
408
jest "Syntax Error: Invalid or unexpected token" with .png
I had the same error and resolved it by creating a assetsTransformer.js: Then add this to your jest ...
407
jest Watch mode stopped working on macOS Sierra
I had the same issue Upgrading watchman with brew install watchman to v4.7.0 fixed it. ...
397
material ui Module not found: Can't resolve 'material-ui-icons/Menu' Martial Next
For anyone else experiencing this issue: npm install @material-ui/icons https://www.npmjs.com/packag...
391
javascript How to configure React Native (Expo) project to use AirBnB's React rules via ESLint?
This is what I do in React and React Native: Step 1 Step 2 Backup your eslintrc file in case you wan...
383
yarn ERROR: There are no scenarios; must have at least one.
You've got the wrong yarn 😄 The Yarn you're executing comes from the cmdtest package: http://manpag...
378
webpacker localIdentName option moved in css-loader configuration
I faced same issue after upading css-loader but I solved it If you check css-loader readme ...
376
react native gesture handler Execution failed for task ':react-native-gesture-handler:compileDebugJavaWithJavac'
@zmGitHub npm i jetifier npx jetify fixed it for me on rn 0.6 I am fixing a incompatibility issue re...
358
atom Sometimes opening a file, Atom does not open in a new tab
This feature is called Pending Pane Items (formerly known as Preview Tabs) – this allows you to quic...
352
axios POST request works in Browser but not on Node
This might be considered a duplicate of #789 I was able to use the form-data package with Axios in n...
348
angular Cyclic dependency error with HttpInterceptor
I resolved simply not setting authService in constructor but getting in the intercept function. ...
337
lodash Find if array includes all elements from another array
You can do _.difference(subset superset).length === 0 to achieve this currently ...
333
fetch Error when POST file multipart/form-data
Setting the Content-Type header manually means it's missing the boundary parameter Remove that heade...
328
amplify js Uncaught ReferenceError: global is not defined in latest Angular 6 RC
Just for reference I have passed through this issue with adding these lines on my index.html head: ...
328
yarn Installation Problem: .yarn-metadata.json: Unexpected end of JSON input
I triggered this condition after a failed install of lodash.isfunction: If you trigger this you can ...
320
sequelize Class constructor Model cannot be invoked without 'new' and how getter v4 work?
Intypescript case my solution was to change target from es5 to es6 Hi all ...
310
yarn ERROR: [Errno 2] No such file or directory: 'add'
I was facing the same problem I am using Ubuntu (17.04) and used sudo apt install yarn to install ya...
301
react TypeError: func.apply is not a function / Uncaught TypeError: destroy is not a function
TypeError: destroy is not a function This is the real error and indicates that you're returning a va...
296
jest requestAnimationFrame warning with React 16
@mbifulco I managed to get this working for all test cases by loading a simple shim before each spec...
296
webpack webpack 4: access the mode flag from webpack.config.js file
This seems to work correctly with --mode production -p and <no flag> Do you want to request a featur...
284
webpack Webpack gives $ is not defined or jQuery is not defined error in console
Just use like this or add to webpack Do you want to request a feature or report a bug? What is the c...
284
yarn There appears to be trouble with your network connection. Retrying...
Adding this comment for other Googlers: What worked for me was increasing the Yarn network timeout: ...