profile
viewpoint
Dan Abramov gaearon @facebook http://twitter.com/dan_abramov Working on @reactjs. Co-author of Redux and Create React App. Building tools for humans.

acdlite/redux-router 2336

Redux bindings for React Router – keep your router state inside your Redux store

gaearon/babel-plugin-react-transform 1100

Babel plugin to instrument React components with custom transforms

alexkuz/react-json-tree 968

React JSON Viewer Component, Extracted from redux-devtools

bvaughn/react-devtools-experimental 967

Experimental rewrite of the React DevTools extension

gaearon/ama 220

Ask me anything!

cavinsmith/bdsm.js 55

Background Dominant Stripe Manipulator

acdlite/react 20

A declarative, efficient, and flexible JavaScript library for building user interfaces.

gaearon/awesome-react 16

A collection of awesome React libraries, resources and shiny things.

issue closedfacebook/react

Bug: Unexpected warning in react-hooks/exhaustive-deps using optional chaining operator

When the optional chaining operator (?.) is used inside a hook and the variable is already listed in the dependencies eslint-plugin-react-hooks reports an unexpected "missing dependency" warning. Replacing ?. with . produces the expected behaviour: the warning is no longer reported.

I would expect that the optional chaining operator (?.) be handled as normal property access (.) in the context of this validation.

React version: 16.13.1 eslint-plugin-react-hooks version: 4.0.2

Steps To Reproduce

Notice that foo is both referenced inside the code in useEffect and is listed as a dependency.

import React, {useEffect} from 'react';

const getFoo = () => undefined;
const doSomethingWith = (foo) => {};

export default () => {
  const foo = getFoo();

  useEffect(() => {
    if (foo?.bar) {
      doSomethingWith(foo);
    }
  }, [foo]);

  return null;
};

<details> <summary>package.json</summary>

{
  "name": "react-hooks-bug",
  "version": "1.0.0",
  "description": "",
  "license": "ISC",
  "scripts": {
    "test": "eslint test.js"
  },
  "dependencies": {
    "babel-eslint": "^10.1.0",
    "eslint": "^7.1.0",
    "eslint-plugin-react-hooks": "^4.0.2"
  },
  "eslintConfig": {
    "parser": "babel-eslint",
    "parserOptions": {
      "sourceType": "module"
    },
    "plugins": [
      "react-hooks"
    ],
    "rules": {
      "react-hooks/exhaustive-deps": "warn"
    }
  }
}

</details>

The current behavior

The following warning is reported:

warning React Hook useEffect has a missing dependency: 'foo?.bar'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

The expected behavior

No warning should be reported.

Additional notes

With the following code, which only replaces ?. with ., eslint-plugin-react-hooks behaves as expected, that is no warning is reported. (Of course this fails at runtime when foo is undefined).

import React, {useEffect} from 'react';

const getFoo = () => undefined;
const doSomethingWith = (foo) => {};

export default () => {
  const foo = getFoo();

  useEffect(() => {
    if (foo.bar) {
      doSomethingWith(foo);
    }
  }, [foo]);

  return null;
};

closed time in 11 hours

jcestibariz

issue commentfacebook/react

Bug: Unexpected warning in react-hooks/exhaustive-deps using optional chaining operator

eslint-plugin-react-hooks@4.0.4

jcestibariz

comment created time in 11 hours

push eventfacebook/react

Toru Kobayashi

commit sha fb735423bb10ae7d23ae42470620e963b8110163

Fix rollup validate script (#18900) * Revert "Revert "deps: update ESLint version to v7 (#18897)" (#18899)" This reverts commit 84fd4b853fd64651abf0b84f4ca879a9e43a106a. * fix rollup validate script

view details

push time in 12 hours

PR merged facebook/react

Fix rollup validate script CLA Signed

<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory.

Before submitting a pull request, please make sure the following is done:

  1. Fork the repository and create your branch from master.
  2. Run yarn in the repository root.
  3. If you've fixed a bug or added code that should be tested, add tests!
  4. Ensure the test suite passes (yarn test). Tip: yarn test --watch TestName is helpful in development.
  5. Run yarn test-prod to test in the production environment. It supports the same options as yarn test.
  6. If you need a debugger, run yarn debug-test --watch TestName, open chrome://inspect, and press "Inspect".
  7. Format your code with prettier (yarn prettier).
  8. Make sure your code lints (yarn lint). Tip: yarn linc to only check changed files.
  9. Run the Flow typechecks (yarn flow).
  10. If you haven't already, complete the CLA.

Learn more about contributing: https://reactjs.org/docs/how-to-contribute.html -->

Summary

This reverts #18899 and re-enables #18897. The issue is caused by https://github.com/eslint/eslint/pull/12888 because ESLint v7 ignores node_modules/* in subdirectories. To fix this, I've add !/build/node_modules/* into eslintignore for the rollup validate script. I've tested this with yarn lint-build. Is there anything else I have to test? Should I add a check to run yarn lint-build at every PRs?

<!-- Explain the motivation for making this change. What existing problem does the pull request solve? -->

Test Plan

yarn lint-build

<!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. -->

➜  yarn lint-build
yarn run v1.22.4
$ node ./scripts/rollup/validate/index.js
Checking if files exist in ./build/react-native/implementations/*.js...
Found 12 bundles.

Checking if files exist in ./build/node_modules/*/umd/*.js...
Found 32 bundles.

Checking if files exist in ./build/node_modules/*/*.js...
Found 54 bundles.

Checking if files exist in ./build/node_modules/*/cjs/*.js...
Found 90 bundles.

Linting rn bundles...
Linted rn bundles successfully!

Linting umd bundles...
Linted umd bundles successfully!

Linting cjs bundles...
Linted cjs bundles successfully!

✨  Done in 12.83s.
+163 -31

1 comment

4 changed files

koba04

pr closed time in 12 hours

pull request commentfacebook/react

Proposal: react-hooks/exhaustive-deps: a more customizable additionalHooks

Could be something like

additionalHooks: [
  [{ test: /regex/, callbackIndex: 3 }],
  ...
]
dvoytenko

comment created time in 12 hours

pull request commentfacebook/react

Proposal: react-hooks/exhaustive-deps: a more customizable additionalHooks

I think we might want to think more about the API here. What if you want to use a regex and put it in the map? The existing feature supports regexes. It is also a bit confusing to have two independent options. Why does one of them win? What if a regex matches in one but the key matches in the other one?

dvoytenko

comment created time in 12 hours

pull request commentfacebook/react

Fix: bug (styles/lastProp).hasOwnProperty is not a function

Thanks for the PR. Can you speak about the actual use case where you're running into this? In general proto-less objects aren't very common in JS and you can't get one accidentally, so it is not clear to me that there is value in going the extra mile to support them for this case. It's not that it hurts, but then we need to be very concrete about all the places where they're allowed and add coverage to avoid regressions. It's not obvious to me that this is worth the maintenance overhead.

eddyw

comment created time in 12 hours

push eventfacebook/react

Julien Deniau

commit sha 8abc202c7fc73fdfcd9443b00d09d06da4b5cbb1

[eslint-plugin-react-hooks] Prefer recommended eslint configuration (#18951) * [eslint-plugin-react-hooks] Prefer recommended eslint configuration * Update README.md Co-authored-by: Dan Abramov <dan.abramov@gmail.com>

view details

push time in 12 hours

push eventjdeniau/react

Dan Abramov

commit sha 082c6f833aab3dd4fe0f374ce6e6110004b816ee

Update README.md

view details

push time in 12 hours

PR merged facebook/react

[eslint-plugin-react-hooks] Prefer recommended eslint configuration CLA Signed

<!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory.

Before submitting a pull request, please make sure the following is done:

  1. Fork the repository and create your branch from master.
  2. Run yarn in the repository root.
  3. If you've fixed a bug or added code that should be tested, add tests!
  4. Ensure the test suite passes (yarn test). Tip: yarn test --watch TestName is helpful in development.
  5. Run yarn test-prod to test in the production environment. It supports the same options as yarn test.
  6. If you need a debugger, run yarn debug-test --watch TestName, open chrome://inspect, and press "Inspect".
  7. Format your code with prettier (yarn prettier).
  8. Make sure your code lints (yarn lint). Tip: yarn linc to only check changed files.
  9. Run the Flow typechecks (yarn flow).
  10. If you haven't already, complete the CLA.

Learn more about contributing: https://reactjs.org/docs/how-to-contribute.html -->

Summary

<!-- Explain the motivation for making this change. What existing problem does the pull request solve? -->

The documentation of eslint-plugin-react-hooks provide the recommended configuration below the not-recommended one. It looks to me that the recommended way should be on the top, and the non-recommended should be less visible.

Test Plan

<!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. -->

Does not seems to need a test plan 😃

+14 -11

3 comments

1 changed file

jdeniau

pr closed time in 12 hours

push eventfacebook/react

Yann アウネ Eves

commit sha 4821d609e99f6bd6454279ee2a82448703d2f616

fix(eslint-plugin-react-hooks): Added matching for nullish coalescing and optional chaining of dependencies, relates to #18985 (#19008)

view details

push time in 12 hours

PR merged facebook/react

fix(eslint-plugin-react-hooks): Support nullish coalescing and optional chaining of dependencies CLA Signed

Relates to #18985

Summary

In conditions where optional chaining is used inside the useEffect hook, the react-hooks/exhaustive-deps rule falsely flags missing dependencies. This change adds some logic to the linting rules to also match dependencies with optional chaining.

Test Plan

Have added tests to cover the following valid scenarios that were previously failing:

// Nullish coalescing
function MyComponent(props) {
  useEffect(() => {
    console.log(props.foo?.bar?.baz ?? null);
  }, [props.foo]);
}
// Optional chaining
function MyComponent(props) {
  useEffect(() => {
    console.log(props.foo?.bar);
  }, [props.foo?.bar]);
}
// Normal and optional chaining
function MyComponent(props) {
  useEffect(() => {
    console.log(props.foo);
    console.log(props.foo?.bar);
  }, [props.foo]);
}
// Optional chaining with prototype method
function MyComponent(props) {
  useEffect(() => {
    console.log(props.foo?.toString());
  }, [props.foo]);
}
+55 -2

3 comments

2 changed files

yanneves

pr closed time in 12 hours

pull request commentfacebook/react

Proposal: react-hooks/exhaustive-deps: a more customizable additionalHooks

Mind updating? Let's get this in.

dvoytenko

comment created time in 14 hours

issue closedfacebook/react

Bug: react-hooks/exhaustive-deps misses a case with useCallback

The following causes an eslint warning (as it should)

const callback = useCallback(()=> cb(), [])

React Hook useCallback has a missing dependency: 'cb'. Either include it or remove the dependency array. If 'cb' changes too often, find the parent component that defines it and wrap that definition in useCallback. (react-hooks/exhaustive-deps)eslint

However, the following does not cause the warning

const callback = useCallback(cb, [])

but it should because this line is exposed to the same stale closure bug as the first.

(Maybe this is an antipattern, but in any case, the linter should be able to notice the problem, because this pattern can be used to "get around" the warning)

React version: 16.12.0

Link to code example: Codesandbox

The current behavior

The linter only notices that the function is missing from the deps array if it is in the form useCallback(() => cb(), [])

The expected behavior

The linter should notice that the function is missing from the deps array in the following form: useCallback(cb, [])

closed time in 21 hours

jdolearydl

issue commentfacebook/react

Bug: react-hooks/exhaustive-deps misses a case with useCallback

Pretty sure this has been fixed.

jdolearydl

comment created time in 21 hours

issue closedfacebook/react

[eslint-plugin-react-hooks] async functions should be allowed for custom effects

Consider the following code:

useAsyncEffect(async () => {
  await foo()
}, []);

Eslint give the following error:

  11:18  error  Effect callbacks are synchronous to prevent race conditions. Put the async function inside:

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

There are 2 problems with that:

  1. The error is provided by react-hooks/exhaustive-deps, but this has nothing to do with deps or exhaustiveness. I can't disable this warning without disable actually checking for exhaustive deps.
  2. In general the error is bogus. Statement "Effect callbacks are synchronous to prevent race conditions" is only true for built-in effects, and is definitely not true for useAsyncEffect, which built specifically to support asynchronous callbacks.

eslint-plugin-react-hooks version: 4.0.0

The current behavior

react-hooks/exhaustive-deps gives an error for this code

The expected behavior

react-hooks/exhaustive-deps should not give an error for this code

closed time in 21 hours

vkurchatkin

issue commentfacebook/react

[eslint-plugin-react-hooks] async functions should be allowed for custom effects

Fixed in eslint-plugin-react-hooks@4.0.3 by removing the flawed heuristic.

vkurchatkin

comment created time in 21 hours

issue commentfacebook/react

[eslint-plugin-react-hooks] false positive with useFocusEffect

Removed in eslint-plugin-react-hooks@4.0.3.

leethree

comment created time in 21 hours

pull request commentfacebook/react

Document `additionalHooks` option

We've tried the heuristic, but I had to revert it because too many false positives are being reported (https://github.com/facebook/react/pull/19004). So I'm happy to take this PR as an alternative, if you'd like to resubmit it.

airjp73

comment created time in 21 hours

pull request commentfacebook/react

Feature: Add support to `exhaustive-deps` rule for any hook ending with `Effect`

This is removed in eslint-plugin-react-hooks@4.0.3. Thanks all for the input.

airjp73

comment created time in 21 hours

issue closedfacebook/react

Bug: Cannot use **use...Effect** names for custom hooks definition

I had following code:

export const useSummaryHeaderActionsEffect = (): void => {
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(fetchAction);
    }, [dispatch]);
};

which is called in component like:

export const SummaryHeader: FC = () => {
    useSummaryHeaderActionsEffect();
    ...
}

and I kept receiving this error on lint (some content anonymised):

TypeError: Cannot read property 'type' of undefined
Occurred while linting ...SummaryHeader.tsx:9
    at visitCallExpression (node_modules/eslint-plugin-react-hooks/cjs/eslint-plugin-react-hooks.development.js:823:24)
    at node_modules/eslint/lib/linter/safe-emitter.js:45:58
    at Array.forEach (<anonymous>)
    at Object.emit (node_modules/eslint/lib/linter/safe-emitter.js:45:38)
    at NodeEventGenerator.applySelector (node_modules/eslint/lib/linter/node-event-generator.js:254:26)
    at NodeEventGenerator.applySelectors (node_modules/eslint/lib/linter/node-event-generator.js:283:22)
    at NodeEventGenerator.enterNode (node_modules/eslint/lib/linter/node-event-generator.js:297:14)
    at CodePathAnalyzer.enterNode (node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:634:23)
    at node_modules/eslint/lib/linter/linter.js:936:32
    at Array.forEach (<anonymous>)
    at runRules (node_modules/eslint/lib/linter/linter.js:931:15)
    at Linter._verifyWithoutProcessors (node_modules/eslint/lib/linter/linter.js:1157:31)
    at Linter._verifyWithConfigArray (node_modules/eslint/lib/linter/linter.js:1255:21)
    at Linter.verify (node_modules/eslint/lib/linter/linter.js:1210:25)
    at Linter.verifyAndFix (node_modules/eslint/lib/linter/linter.js:1400:29)
    at verifyText (node_modules/eslint/lib/cli-engine/cli-engine.js:230:48)
    at CLIEngine.executeOnFiles (node_modules/eslint/lib/cli-engine/cli-engine.js:798:28)
    at Object.execute (node_modules/eslint/lib/cli.js:212:111)
    at Object.<anonymous> (node_modules/eslint/bin/eslint.js:107:28)
    .
    .
    .
{
  killed: false,
  code: 2,
  signal: null,
  cmd: 'eslint --quiet SummaryHeader.tsx'
}

until I changed the name of my custom hook from useSummaryHeaderActionsEffect to useSummaryHeaderActionsOnMount.

So obviously name pattern use...Effect got the fella confused when doing his job.

It doesn't seem to be a behaviour by design, otherwise I'd expect proper ESLint hint saying I'm using not-allowed name pattern.

React version: "react": "16.13.1", "@typescript-eslint/eslint-plugin": "2.26.0", "eslint-plugin-react-hooks": "4.0.0", "eslint": "6.8.0",

The current behavior

Cannot use name pattern use...Effect for custom hooks.

The expected behavior

It's possible to use name pattern use...Effect for custom hooks or eslint-plugin-react-hooks warns you it is not desired.

closed time in 21 hours

japutko

issue commentfacebook/react

Bug: Cannot use **use...Effect** names for custom hooks definition

Fixed in eslint-plugin-react-hooks@4.0.3.

japutko

comment created time in 21 hours

push eventfacebook/react

Dan Abramov

commit sha 67e130fc686f3e5d9e0404fddc6861333d81dc23

eslint-plugin-react-hooks@4.0.3

view details

push time in 21 hours

push eventfacebook/react

Dan Abramov

commit sha bb2239dc90015ced86177adc522de568198e2edc

Revert "Feature: Add support to `exhaustive-deps` rule for any hook ending with `Effect` (#18580)" (#19004) This reverts commit 5ac9ca72dfb73a06157bb177cd695f6b77fc900e.

view details

push time in 21 hours

PR merged facebook/react

Revert "Add support to `exhaustive-deps` rule for any hook ending with `Effect`" CLA Signed React Core Team

Reverts #18580.

I thought we might try this but there's both bugs in the implementation (https://github.com/facebook/react/issues/19001) and too many false positives (https://github.com/facebook/react/pull/18580#issuecomment-633513512, https://github.com/facebook/react/pull/18580#issuecomment-632269045, https://github.com/facebook/react/issues/18858, https://github.com/facebook/react/issues/18888). I think it's clear this heuristic hasn't worked out.

+8 -156

3 comments

2 changed files

gaearon

pr closed time in 21 hours

issue commentfacebook/react

[eslint-plugin-react-hooks] false positive with useFocusEffect

We're going to revert this heuristic, so no changes necessary to React Navigation.

leethree

comment created time in 21 hours

pull request commentfacebook/react

Feature: Add support to `exhaustive-deps` rule for any hook ending with `Effect`

I'm going to have to revert this because the heuristic has too many reasonable false positives. https://github.com/facebook/react/pull/19004

airjp73

comment created time in 21 hours

PR opened facebook/react

Revert "Add support to `exhaustive-deps` rule for any hook ending with `Effect`"

Reverts #18580.

I thought we might try this but there's both bugs in the implementation (https://github.com/facebook/react/issues/19001) and too many false positives (https://github.com/facebook/react/pull/18580#issuecomment-633513512, https://github.com/facebook/react/pull/18580#issuecomment-632269045, https://github.com/facebook/react/issues/18858, https://github.com/facebook/react/issues/18888). I think it's clear this heuristic hasn't worked out.

+8 -156

0 comment

2 changed files

pr created time in 21 hours

issue commentfacebook/react

Bug: Cannot use **use...Effect** names for custom hooks definition

We're going to revert https://github.com/facebook/react/pull/18580 which will fix this too.

japutko

comment created time in 21 hours

create barnchgaearon/react

branch : revert-lint

created branch time in 21 hours

pull request commentfacebook/react

Feature: Add support to `exhaustive-deps` rule for any hook ending with `Effect`

One thing we could do is to only run checks if you have a function followed by an array, in addition to ending with Effect. But I'm leaning towards reverting this altogether.

airjp73

comment created time in 21 hours

push eventfacebook/react

Dan Abramov

commit sha 3ca1904b37ad1f527ff5e31b51373caea67478c5

react-refresh@0.8.3

view details

push time in 4 days

pull request commentfacebook/react

Resolve an edge case where ref.node can be falsy

Out in react-refresh@0.8.3

yjimk

comment created time in 4 days

push eventfacebook/react

yjimk

commit sha 0aa4cc544c2ef93f53eea9373a35228a99f71784

Resolve an edge case where ref.node can be falsy (#18984) Co-authored-by: Jimmy Cann <jimmy.cann@ironstar.io>

view details

push time in 4 days

PR merged facebook/react

Resolve an edge case where ref.node can be falsy CLA Signed

Summary

Discovered an edge case on a Next.js project where ref.node can be falsy. This causes the development server to become unable to compile correctly, and subsequently fails.

Test Plan

Apologies, the project in question is proprietary, I cannot use it to demonstrate this case, it's also not the easier thing to replicate.

I'm hoping the simplicity of the change in question will be enough to allow it to be merged

+1 -0

2 comments

1 changed file

yjimk

pr closed time in 4 days

issue closedfacebook/react

Bug: lazy loading not work on concurrent mode 0.0.0-experimental-e5d06e34b

React version: 0.0.0-experimental-e5d06e34b React-native: 0.62

Steps To Reproduce

  1. below code work well
import Routes from './Routes';

const App = () => {
  const resource = useState(() => wrapPromise(initialize()))[0];

  return (
     <SuspenseList tail="collapsed" revealOrder="forwards">
        <Suspense fallback={<View />}>
             <Initializer {...{resource}} />
        </Suspense>
        <Suspense fallback={<View />}>
             <Routes />
        </Suspense>
     </SuspenseList>       
  );
};
  1. but when change routes to lazy mode that won't work on react-native
const Routes = React.lazy(() => {
   return import('./Routes.js');
});

The current behavior

React.lazy don't work in this version of experimental

The expected behavior

That work well in 0.0.0-experimental-5faf377df When I use inline import instead that work well

closed time in 5 days

hosseinmd

issue commentfacebook/react

Bug: lazy loading not work on concurrent mode 0.0.0-experimental-e5d06e34b

SuspenseList has been renamed to unstable_SuspenseList in experimental releases. That's probably why the issue is happening.

As an aside, using experimental releases with RN is not really supported at this moment.

hosseinmd

comment created time in 5 days

pull request commentfacebook/react

[Fresh] Fix edge case with early function call

I released this PR as 0.4.3.

gaearon

comment created time in 5 days

pull request commentfacebook/react

[Fresh] Fix edge case with early function call

What is the actual code triggering this in your case?

gaearon

comment created time in 5 days

push eventreactjs/reactjs.org

Jack Hsu

commit sha f81b909ce97dc253998a192f367551cb2b40d66f

Add a link to Nx under the Flexible Toolchains section (#2979)

view details

push time in 5 days

PR merged reactjs/reactjs.org

Add a link to Nx under the Flexible Toolchains section CLA Signed

Hi 👋 ,

Full disclaimer: I'm on the Nx core team -- in charge of the React support.

We've been gaining some traction in the React community (already widely used by the Angular community), and I think it would be a useful tool for React teams using monorepos.

More info in README and docs site:

  • https://www.npmjs.com/package/@nrwl/workspace
  • https://nx.dev/react

PS. I added the link to Nx under Neutrino (I assume this section is sorted alphabetically).

+2 -0

0 comment

1 changed file

jaysoo

pr closed time in 5 days

pull request commentfacebook/react

Separate _owner from _debugOwner

By the way this changes DevTools behavior (which is why CI tests are failing)

Yes, hence one of the TODOs. :-)

gaearon

comment created time in 6 days

Pull request review commentfacebook/react

Separate _owner from _debugOwner

 export function createFiberFromTypeAndProps(   type: any, // React$ElementType   key: null | string,   pendingProps: any,-  owner: null | Fiber,+  debugOwner: null | Fiber,

This was already only used for a better error message, and null in prod.

gaearon

comment created time in 6 days

Pull request review commentfacebook/react

Separate _owner from _debugOwner

 function mountIndeterminateComponent(     }      setIsRendering(true);-    ReactCurrentOwner.current = workInProgress;

This is probably unsafe and might break String Refs in Factory Components. Not sure if we support those.

gaearon

comment created time in 6 days

Pull request review commentfacebook/react

Separate _owner from _debugOwner

 describe('ReactFunctionComponent', () => {     expect(function() {       ReactTestUtils.renderIntoDocument(<Child test="test" />);     }).toThrowError(-      __DEV__-        ? 'Function components cannot have string refs. We recommend using useRef() instead.'-        : // It happens because we don't save _owner in production for-          // function components.-          'Element ref was specified as a string (me) but no owner was set. This could happen for one of' +-            ' the following reasons:\n' +-            '1. You may be adding a ref to a function component\n' +-            "2. You may be adding a ref to a component that was not created inside a component's render method\n" +-            '3. You have multiple copies of React loaded\n' +-            'See https://fb.me/react-refs-must-have-owner for more information.',+      'Element ref was specified as a string (me) but no owner was set. This could happen for one of' +

This message was previously inconsistent between DEV and PROD. Now we show the same message.

gaearon

comment created time in 6 days

Pull request review commentfacebook/react

Separate _owner from _debugOwner

 import {   findHostInstance,   findHostInstanceWithWarning, } from 'react-reconciler/src/ReactFiberReconciler';+import {isRendering as ReactCurrentFiberIsRendering} from 'react-reconciler/src/ReactCurrentFiber';

This is a bit awkward. One alternative is to put isRendering onto ReactDebugCurrentFrame itself.

gaearon

comment created time in 6 days

Pull request review commentfacebook/react

Separate _owner from _debugOwner

 import type {Fiber} from './ReactInternalTypes'; import type {Container, SuspenseInstance} from './ReactFiberHostConfig'; import type {SuspenseState} from './ReactFiberSuspenseComponent.old';+import {isRendering as ReactCurrentFiberIsRendering} from './ReactCurrentFiber';

This is actually a bit of a red flag because for third-party renderers, /reflection entry point won't "see" the value. So maybe this is a good motivation to move isRendering into ReactDebugCurrentFrame.

gaearon

comment created time in 6 days

Pull request review commentfacebook/react

Separate _owner from _debugOwner

 function createElement(type, key, props): React$Element<any> {       writable: false,       value: null,     });+    Object.defineProperty(element, '_debugOwner', {

Note: this is Flight. Ignore.

gaearon

comment created time in 6 days

PR opened facebook/react

Separate _owner from _debugOwner

We rely on the element owner for two different behaviors:

  1. Semantic meaning: If an element is created in a class render method, that instance becomes its String Ref Owner.
  2. Debugging info: If an element gets created while rendering an arbitrary fiber, we want to "remember" that for DevTools and some warning messages.

These purposes are currently conflated because we only have element._owner. This field is set inconsistently, e.g. it's set in production only for classes, but in development it's set while rendering function components too. This makes it hard to remove in the future when we remove String Refs.

In this PR, we split these two purposes into element._owner and element_debugOwner. Only String Refs would rely on element._owner, which in this PR is set only for classes. The other DEV-only cases would rely on element._debugOwner.

TODO:

  • [ ] Possibly revert the MountInderterminateComponent case. We may need this if refs worked for Factory Components before.
  • [ ] Change DevTools to rely on _debugOwner for "rendered by" breadcrumbs.
    • [ ] Perhaps, this means we need to flip it, add a PROD _refOwner field, and then keep _owner as the DEV-only one? Then we won't need to change DevTools.
  • [ ] Maybe, put isRendering onto ReactDebugCurrentFrame.
+158 -95

0 comment

19 changed files

pr created time in 6 days

create barnchgaearon/react

branch : debugowner

created branch time in 6 days

issue closedfacebook/react

My website is taking 6mb for loading which is very large.How to reduce this file size or can anybody suggest me any other solution?

I built a website using Node Js, Express, MongoDB, React Js and Next Js. Now the problem is when i load the website it take 5 to 6mb for loading which is very large. There are 3 files which is loaded with the website that take almost 1mb each file.Screenshot is given below indicating those files. I want to know is there any way to reduce this file size or can anybody suggest me any other option to reduce the website loading size? Problem1

closed time in 6 days

Shawan1008

issue commentfacebook/react

My website is taking 6mb for loading which is very large.How to reduce this file size or can anybody suggest me any other solution?

Maybe something like this could help? https://nextjs.org/docs/advanced-features/dynamic-import

I would suggest asking support on Next forums. We use this issue tracker for bugs in React.

Shawan1008

comment created time in 6 days

issue commentfacebook/react

Webpack can't find ReactDOM.createRoot

We’ve added the unstable_ prefix back.

brneto

comment created time in 6 days

issue commentfacebook/react

Identify component as 'pending', when used with useTransition

@natew The rule of the land is just that we want to be able to re-run render at arbitrary times. We also don’t give you guarantees that any particular render result will get committed. So if you subscribe during render you won’t have a good place to unsubscribe.

samdenty

comment created time in 6 days

push eventgaearon/react

Dan Abramov

commit sha 81edd5006603b58e95218447002a635b23f7eb70

Add more versatile URL handling This adds highlighting to links. I've also fixed the URL system so it can match more than one segment at a time. I've also refactored a few things to simplify the code.

view details

push time in 7 days

push eventgaearon/react

Dan Abramov

commit sha 5d2e01ba3476c0bbd20e45aa08ad95a40bee4bf2

Add more versatile URL handling This adds highlighting to links. I've also fixed the URL system so it can match more than one segment at a time. I've also refactored a few things to simplify the code.

view details

push time in 7 days

push eventgaearon/react

Dan Abramov

commit sha 55bf4f399464e227745393d65522004a281d8e67

Add more versatile URL handling This adds highlighting to links. I've also fixed the URL system so it can match more than one segment at a time. I've also refactored a few things to simplify the code.

view details

push time in 7 days

push eventgaearon/react

Dan Abramov

commit sha 5c8f7c84e9f9ed14520cf76ed79a12e2bb9d6c28

Add more versatile URL handling This adds highlighting to links. I've also fixed the URL system so it can match more than one segment at a time. I've also refactored a few things to simplify the code.

view details

push time in 7 days

push eventgaearon/react

Dan Abramov

commit sha 45b7b2c5a92d111c8ec81796d4cb5a4f993d0990

Add more versatile URL handling This adds highlighting to links. I've also fixed the URL system so it can match more than one segment at a time. I've also refactored a few things to simplify the code.

view details

push time in 7 days

push eventgaearon/react

Dan Abramov

commit sha 76182049f219297014773a86f7597dfe917378a3

Highlight active tab links This is actually buggy. 1) Loading Seb/Photos should still highlight Seb on first load 2) Going from Seb to Dan/Photos should highlight Dan

view details

Dan Abramov

commit sha e7a4690484bf690c406519b483f6700517669bc8

Add more versatile URL handling This adds highlighting to links. I've also fixed the URL system so it can match more than one segment at a time. I've also refactored a few things to simplify the code.

view details

push time in 7 days

pull request commentDefinitelyTyped/DefinitelyTyped

fix(react): Remove unstable APIs

I would keep unstable_batchedUpdates and unstable_renderSubtreeIntoContainer. They have a special status because de facto they're widely used, and we can't change their semantics.

eps1lon

comment created time in 8 days

issue commentDefinitelyTyped/DefinitelyTyped

[@types/react] Remove calculateChangedBits from createContext

Personally I'm fine with removing unstable APIs from the typings and recommend declaration merging. It's what we recommend for non-standard HTML attributes as well.

👍

gaearon

comment created time in 8 days

issue commentDefinitelyTyped/DefinitelyTyped

[@types/react] Remove calculateChangedBits from createContext

My main concern is Code aggressively autocompleting parameters that aren't supposed to be used. Which arguably is more of a Code issue. I guess for function arguments this is worse than for JSX props.

Overall, I think if something is not in the docs, it should not be in the typings either. People who want to use it can always any it.

gaearon

comment created time in 8 days

startedmicrosoft/react-native-macos

started time in 8 days

Pull request review commentfacebook/react

DevTools editable props tweaks

 }  .Name {-  color: var(--color-dim);+  color: var(--color-aattribute-name-not-editable);

aattribute?

bvaughn

comment created time in 8 days

issue openedDefinitelyTyped/DefinitelyTyped

[@types/react] Remove calculateChangedBits from createContext

Authors: @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @DovydasNavickas @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei @Jessidhia @saranshkataria @lukyth @eps1lon @zieka @dancerphil @dimitropoulos @disjukr @vhfmag


I've just noticed createContext has a second argument in the type definition. This doesn't make sense and is misleading. That second argument is an unstable API that will likely be removed. It's called unstable_calculateChangedBits but the definition just calls it calculateChangedBits. What's worse, VS Code autocomplete offers to supply it. Could we remove the unstable API from typings or move this overload to the experimental definition?

created time in 8 days

push eventgaearon/react

Dan Abramov

commit sha 106e29ca00e0bdbb2038b98bb6e018705618f2fa

[Frame] Add fixture

view details

push time in 9 days

PR opened facebook/react

[Frame] Add fixture

This adds a shell for routing experiments with Server Components. Although it's using Next, this is currently 100% client-side. I could switch to CRA but I figured in case we want to add something server-side, Next might be easier to play with.

The interesting part is App.js. It's split in a few sections: server product code, server infra code, and client infra code. I tried to follow the rules, i.e. client components don't use server components. There is an exception in the match rendering logic (because we need an entry point into the server for partial frames), but that part should be fully serializable.

I left some comments inline. There's a few notable pieces:

  • <Frame entry="EntryPointName" /> renders a route handler. The rendering is delegated to the actual named entry point. For partial updates, that entry point is conceptually the root.
  • Frames on the server set up a "frame context". Links on the server use it to "ask" which Frame the link should target. The closest ancestor Frame responds with its keypath and the hosted content.
  • Links on the server pass the target Frame keypath and the content (which in reality would be something like an entry point URL rather than a tree) to the client Link.
  • Client Link, when clicked, will find the ancestor Client Frame with the target provided by the Server Link. It will then tell the Client Frame to show the content embedded in the Link.
  • On the server, Frames push their entry names and the consumed URL segments into the context. Server Links will pass a serialized version of this context to the Client Link as part of the entrypoint. Then, on the server, we will restore the Frame hierarchy above the requested subtree, based on the serialized Frame context. This is how we make Link-Frame matching work for subsequent navigations on the server.
  • There is an input to demonstrate that the client state lines up during compatible updates.

Unresolved questions:

  • Where does the cache live?
  • How is the Back button handled?
  • What would a realistic entry point API look like?
  • How could more complex URLs be handled?
+5845 -0

0 comment

6 changed files

pr created time in 9 days

create barnchgaearon/react

branch : frame

created branch time in 9 days

issue commentfacebook/react

Double-render in development could be opt-in

We've actually silenced the second render logs on master by overriding console.log. But this is obviously controversial. I do wonder if you're right and we should just do this for class lifecycles. Although then it will be harder to fix issues that occur due to a render side effect.

bbenezech

comment created time in 9 days

issue commentreactjs/reactjs.org

Older React version documentation links are broken.

Yeah I think it's likely the search only works on the new website.

kartiksharma1607

comment created time in 9 days

issue commentreactjs/reactjs.org

Update docs to use hooks

I don't think there would be any significant impact given we've used function since 2013 and people sometimes prefer arrows anyway.

selbekk

comment created time in 11 days

issue commentreactjs/reactjs.org

Update docs to use hooks

Just wanted to note this is still very much on our minds. We might start looking into this soon-ish. One challenge is how to coordinate translations. Since this is a big rewrite. cc @tesseralis curious if you have tips on how we could approach this.

selbekk

comment created time in 12 days

pull request commentfacebook/react

Update inaccurate mapChildren comment

Note it should care of merging with the old key automatically.

rickyvetter

comment created time in 12 days

push eventfacebook/react

Ricky Vetter

commit sha 121af3143c7164a196420b080cb31d0ef07d5dff

Update inaccurate mapChildren comment (#18931) The function you provide will only be passed a child and an index. It will not be passed a key. This is confirmed in the source, the Flow types, and the jsdoc comments.

view details

push time in 12 days

PR merged facebook/react

Update inaccurate mapChildren comment CLA Signed

The function you provide will only be passed a child and an index. It will not be passed a key. This is confirmed in the source, the Flow types, and the jsdoc comments.

Summary

I was actually looking for a child map api that would expose keys and noticed this comment. It gave me the wrong impression and took a few minutes to re-affirm my understanding of React.Children and how it works. Removing this inaccuracy to hopefully prevent a similar misunderstanding in the future.

Test Plan

I ran absolutely no tests. This is a non-jsdoc comment-only change.

+1 -1

3 comments

1 changed file

rickyvetter

pr closed time in 12 days

pull request commentfacebook/metro

Allow objects that only wrap react components

This really needs a test, we can’t merge without one. I can try to carve out time next week but in general you should be able to find an existing test (if this path is covered, that is) and copy paste it and then tweak it.

jfrolich

comment created time in 12 days

issue commentfacebook/react

[eslint-plugin-react-hooks] Bug: warning on `useWithoutEffectSuffix`

Appreciate you did the work! I was feeling a bit tired today and this was really nice.

surgeboris

comment created time in 14 days

pull request commentfacebook/react

[eslint-plugin-react-hooks] useWithoutEffectSuffix fix (#18902)

released in 4.0.2

surgeboris

comment created time in 14 days

push eventfacebook/react

Dan Abramov

commit sha 43063fd8442c5dfa927b4cc423bae1bdbeac7132

eslint-plugin-react-hooks@4.0.2

view details

push time in 14 days

push eventfacebook/react

Dan Abramov

commit sha f6ff4c43dde9f208dcd3d8d7115cfedb4f3b8aa5

Update changelog

view details

push time in 14 days

push eventfacebook/react

Boris Sergeev

commit sha 487c693846dbe58a68a410c658699d27386323b3

[eslint-plugin-react-hooks] useWithoutEffectSuffix fix (#18902) (#18907) * [eslint-plugin-react-hooks] reproduce bug with a test and fix it (#18902) Since we only reserve `-Effect` suffix, react-hooks/exhaustive-deps is expected to succeed without warning on a custom hook which contains -Effect- in the middle of it's name (but does NOT contain it as a suffix). * [eslint-plugin-react-hooks] reproduced bug with a test and fix it Since we only reserve `-Effect` suffix, react-hooks/exhaustive-deps is expected to succeed without warning on a render helper which contains -use- in the middle of it's name (but does NOT contain it as a prefix, since that would violate hook naming convetion). Co-authored-by: Boris Sergeyev <boris.sergeyev@quolab.com>

view details

push time in 14 days

pull request commentfacebook/react

[eslint-plugin-react-hooks] useWithoutEffectSuffix fix (#18902)

thanks!

surgeboris

comment created time in 14 days

PR merged facebook/react

[eslint-plugin-react-hooks] useWithoutEffectSuffix fix (#18902) CLA Signed

Summary

Due to a bug react-hooks/exhaustive-deps currently warns whenever name contains -Effect- (even if it does NOT contain it as a suffix).

Since we only reserve -Effect suffix, react-hooks/exhaustive-deps is expected to succeed without warning on a custom hook which contains -Effect- in the middle of it's name (but does NOT contain it as a suffix).

Test Plan

Added a testcase that fails when fix isn't present:

$ yarn test ExhaustiveDeps
yarn run v1.22.4
$ cross-env NODE_ENV=development jest --config ./scripts/jest/config.source.js ExhaustiveDeps
 FAIL  packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
  react-hooks
    valid
      ✕ 
function MyComponent(props) {
  useWithoutEffectSuffix(() => {
    console.log(props.foo);
  }, []);
}
 (282ms)

  ● react-hooks › valid › 
function MyComponent(props) {
  useWithoutEffectSuffix(() => {
    console.log(props.foo);
  }, []);
}


    assert.strictEqual(received, expected)

    Expected value to strictly be equal to:
      0
    Received:
      1
    
    Message:
      Should have no errors but had 1: [
      {
        ruleId: 'react-hooks',
        severity: 1,
        message: "React Hook useWithoutEffectSuffix has a missing dependency: 'props.foo'. Either include it or remove the dependency array.",
        line: 5,
        column: 6,
        nodeType: 'ArrayExpression',
        endLine: 5,
        endColumn: 8,
        suggestions: [ [Object] ]
      }
    ]

      at testValidTemplate (node_modules/eslint/lib/rule-tester/rule-tester.js:460:20)
      at Object.<anonymous> (node_modules/eslint/lib/rule-tester/rule-tester.js:662:25)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.13s, estimated 3s
Ran all test suites matching /ExhaustiveDeps/i.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Once fix is added test succeeds:

$ yarn test ExhaustiveDeps
yarn run v1.22.4
$ cross-env NODE_ENV=development jest --config ./scripts/jest/config.source.js ExhaustiveDeps
 PASS  packages/eslint-plugin-react-hooks/__tests__/ESLintRuleExhaustiveDeps-test.js
  react-hooks
    valid
      ✓ 
function MyComponent(props) {
  useWithoutEffectSuffix(() => {
    console.log(props.foo);
  }, []);
}
 (229ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.839s, estimated 9s
Ran all test suites matching /ExhaustiveDeps/i.
Done in 4.30s.
+19 -1

3 comments

2 changed files

surgeboris

pr closed time in 14 days

issue commentpmmmwh/react-refresh-webpack-plugin

Try integrating into Create React App

Note there are some pending fixes that haven't made into CRA version yet.

gaearon

comment created time in 14 days

Pull request review commentfacebook/react

[eslint-plugin-react-hooks] useWithoutEffectSuffix fix (#18902)

 const tests = {         }       `,     },+    {+      code: normalizeIndent`+        function MyComponent(props) {+          useWithoutEffectSuffix(() => {+            console.log(props.foo);+          }, []);+        }+      `,+    },+    {+      only: true,

only

surgeboris

comment created time in 14 days

Pull request review commentfacebook/react

[eslint-plugin-react-hooks] useWithoutEffectSuffix fix (#18902)

 function getReactiveHookCallbackIndex(calleeNode, options) {       // useImperativeHandle(ref, fn)       return 1;     default:-      if (node === calleeNode && node.name.match(/use.+Effect/)) {+      if (node === calleeNode && node.name.match(/use.+Effect$/)) {

Should we also start it with ^?

surgeboris

comment created time in 14 days

issue commentfacebook/react

Bug: IE11 with Suspense doesn't support direct child with inline display: flex style

Any hunch as to why IE behavior is different?

AdrianoRuberto

comment created time in 14 days

issue commentfacebook/react

[eslint-plugin-react-hooks] Bug: warning on `useWithoutEffectSuffix`

Would you like to submit a failing test case and/or a fix? You can search for ExhaustiveDeps-test.js in the codebase. That would be very helpful!

surgeboris

comment created time in 14 days

pull request commentfacebook/react

deps: bump ESLint version to v7

I reverted in https://github.com/facebook/react/pull/18899 because this failed master builds. It seems like we only ran this task on master? @koba04 mind looking into this?

koba04

comment created time in 15 days

push eventfacebook/react

Dan Abramov

commit sha 84fd4b853fd64651abf0b84f4ca879a9e43a106a

Revert "deps: update ESLint version to v7 (#18897)" (#18899) This reverts commit 039ad34a059981b1ba972e205cea8347462cf492.

view details

push time in 15 days

PR merged facebook/react

Revert "deps: bump ESLint version to v7" CLA Signed

Reverts facebook/react#18897

+30 -158

0 comment

3 changed files

gaearon

pr closed time in 15 days

create barnchfacebook/react

branch : revert-18897-eslint-v7

created branch time in 15 days

PR opened facebook/react

Revert "deps: bump ESLint version to v7"

Reverts facebook/react#18897

+30 -158

0 comment

3 changed files

pr created time in 15 days

issue closedfacebook/react

[eslint-plugin-react-hooks] false positive with useFocusEffect

Upgraded eslint-plugin-react-hooks to 4.0.0, it's showing errors on React-Navigation's useFocusEffect hook.

import { useFocusEffect } from '@react-navigation/native';

  useFocusEffect(
    React.useCallback(() => {
      const unsubscribe = API.subscribe(userId, user => setUser(user));
      return () => unsubscribe();
    }, [userId])
  );

(example copied from React-Navigation documentation)

The current behavior

Lint error:

React Hook useFocusEffect received a function whose dependencies are unknown. Pass an inline function instead.

The expected behavior

The rules shouldn't check the function because it's not a React useEffect hook.

closed time in 15 days

leethree

issue commentfacebook/react

[eslint-plugin-react-hooks] false positive with useFocusEffect

Fixed changelog: https://github.com/facebook/react/commit/14e554b3103cc009c86f48ed927f2552649600a6.

I think we'll need to ask react-navigation to offer an alternative naming for this one to avoid breaking the convention. I'm sorry I didn't catch this earlier. The upside is that people seeing the Effect naming might be a bit confused anyway and try to pass the deps, so this is probably a net positive overall.

leethree

comment created time in 15 days

push eventfacebook/react

Dan Abramov

commit sha 14e554b3103cc009c86f48ed927f2552649600a6

Add missing changelog item

view details

push time in 15 days

issue commentfacebook/react

[eslint-plugin-react-hooks] false positive with useFocusEffect

@surgeboris When I added this changelog, I took twenty minutes to go through all the past PRs, remember the context behind them, and reconstruct it. I'm sorry that I missed one of them.

leethree

comment created time in 15 days

Pull request review commentfacebook/react

Modern Event System: Add scaffolding for createEventHandle

 export function accumulateEnterLeaveListeners(     );   } }++export function getListenerMapKey(+  topLevelType: DOMTopLevelEventType,+  capture: boolean,+): string {+  return `${getRawEventName(topLevelType)}__${capture ? 'capture' : 'bubble'}`;

Firstly, topLevelType isn't onClickCapture, it's literally click.

I wasn't referring to topLevelType, I was referring to registrationName in the external code which eventually gets turned into topLevelType.

Also onClickCapture doesn't really mean that we should use the actual DOM event capture phase, we only use the bubble phase and emulate the capture qualities. For this particular key logic, we want the "real" properties for a given event – as this is important for createEventHandle where we actually use the capture phase and bubble phase specified by the user, rather than our internal emulation system, when dealing with events attached to EventTargets not managed by React.

OK, that makes sense.

trueadm

comment created time in 15 days

more