profile
viewpoint
Sophie Alpert sophiebits Humu California https://sophiebits.com/ I like fixing things. eng at humu! former eng manager of @reactjs at Facebook. ex-@khanacademy. 💎🌸 she/her. kindness, intersectional feminism, music.

facebook/react 149373

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

jonschlinkert/remarkable 4754

Markdown parser, done right. Commonmark support, extensions, syntax plugins, high speed - all in one. Gulp and metalsmith plugins available. Used by Facebook, Docusaurus and many others! Use https://github.com/breakdance/breakdance for HTML-to-markdown conversion. Use https://github.com/jonschlinkert/markdown-toc to generate a table of contents.

reactjs/rfcs 2788

RFCs for changes to React

sindresorhus/object-assign 861

ES2015 Object.assign() ponyfill

kentcdodds/modern-react 207

workshop about React's hottest new features in 16.7.0

sophiebits/adventofcode 17

Advent of Code Solutions

bvaughn/react 12

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

HCSSiM/yp17 5

HCSSiM style for LaTeX

kamens/khan-exercises 4

A framework for building exercises to work with Khan Academy.

Pull request review commentfacebook/react

Bugfix: Missing mode check in resetChildLanes

 function resetChildLanes(completedWork: Fiber) {     (completedWork.tag === LegacyHiddenComponent ||       completedWork.tag === OffscreenComponent) &&     completedWork.memoizedState !== null &&-    !includesSomeLane(subtreeRenderLanes, (OffscreenLane: Lane))+    !includesSomeLane(subtreeRenderLanes, (OffscreenLane: Lane)) &&+    (completedWork.mode & ConcurrentMode) !== NoLanes

(NoMode)

acdlite

comment created time in 7 days

pull request commentfacebook/react

Transfer actualDuration only once for SuspenseList

can’t tell from your summary…

if each child has its own correct time but you’re counting the 1st child n times, 2nd child n – 1 times, etc, then it’s quadratic

conversely, if your time for child k includes the times for children 1 through k – 1, then it’s exponential

sebmarkbage

comment created time in 7 days

issue commentfacebook/react

DevTools: Uncaught error doesn't go away on page refresh

I'm specifically talking about the case where the devtools break due to an uncaught error. A working "Reload" on that error page would also be OK.

sophiebits

comment created time in 9 days

issue closedfacebook/react

Bug: parent will mount earlier than its suspending child

React version: 16.3.1

Steps To Reproduce

  1. use data fetching with suspense in latest release version (not concurrent mode)
  2. render a simple wrapper around SuspendingComponent as child of SuspenseBoundary

Link to code example

The current behavior

parent (wrapper around SuspendingComponent) will mount before child

The expected behavior

parent an child should mount after data received

closed time in 9 days

MHA15

issue commentfacebook/react

Bug: parent will mount earlier than its suspending child

I believe this is intended behavior for legacy (non-concurrent) mode, in order to preserve the invariant that if a render function completes successfully, then effects will run as well – the parent component is immediately hidden afterwards. In concurrent mode you'd see that the parent never completes mounting, which will be the future behavior, and it will be encouraged for anyone using data fetching with suspense to use concurrent mode or at least blocking mode: https://reactjs.org/docs/concurrent-mode-adoption.html#migration-step-blocking-mode.

(I'll remind you also that data fetching with suspense isn't officially supported yet.)

MHA15

comment created time in 9 days

issue commentfacebook/react

Feature proposal: let class component setState second param callback always give the latest state

React tends to not add more than one way to do something if the existing way is already clear and works well. I would say that this.state is quite straightforward and mirrors how you would always access state in a class component (so it’s one less thing to learn). One other minor issue I see with your proposal is that it would make the two arguments easier to confuse as both would take state then. Lastly, I would look to Hooks for where React is primarily evolving toward in the future.

Thanks for submitting this idea but it’s not likely to be implemented, so I’m going to close this.

fantasticsoul

comment created time in 10 days

issue closedfacebook/react

Feature proposal: let class component setState second param callback always give the latest state

Context

I know setState first param can be a updater

(state, props)=> stateChanged;

but why not the second callback param can not supply the latest state in its param list.

this.setState({msg:'new msg'}, (newState)=>{
    console.log(newState);// let user no need to write this.state here
})

Link to code example:

class Test extends React.Component{
  state = {msg:'msg'}
  changeMsg = ()=>{
    this.setState({msg:Date.now()}, (newState)=>{
      console.log(newState);// undefined
      console.log(this.state);// latest state
    });
  }
  render(){
    const msg = this.state.msg;
    return (
      <div>{msg} <input value={msg} onChange={this.changeMsg} /></div>
    );
  }
}

The current behavior

the newState is undefined

The expected behavior

the newState is the latest state

closed time in 10 days

fantasticsoul

issue openedfacebook/react

Bug: eslint exhaustive-deps doesn't recognize JSXIdentifier as used

function Component({reportType}) {
  let Report = Reports[reportType];
  let child = useMemo(() => {
    return <Report />;
  }, [Report]);

says that Report is an unnecessary dependency. It's not.

This is because eslint scope .references does not include JSX. I suspect if you pull in

https://github.com/yannickcr/eslint-plugin-react/blob/master/lib/rules/jsx-uses-vars.js

to your app's config then this won't happen. But maybe we should do something in the Hooks plugin itself too (since the others aren't officially recommended by the React team anyway).

created time in 11 days

issue openedfacebook/react

DevTools: Uncaught error doesn't go away on page refresh

  1. Wait for devtools to hit an error (eg: #18934).
  2. Reload the page.

Expected: Devtools reinitializes cleanly. Actual: Error is still there. Need to hide devtools, reload again, then show devtools to get it to behave.

DevTools version: 4.6.0-6cceaeb67

created time in 11 days

issue openedfacebook/react

DevTools profiler: Error: "Cannot read property 'concat' of undefined"

Describe what you were doing when the bug occurred:

  1. Loaded page.
  2. Fast Refreshed.
  3. Started profiler.
  4. Stopped profiler. Crash.

Please do not remove the text below this line

DevTools version: 4.6.0-6cceaeb67

Call stack: at j (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:40:162638) at N (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:40:161628) at e.getCommitTree (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:40:164582) at ec (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:40:339280) at ci (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:32:59620) at nl (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:32:69923) at Ll (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:32:110996) at qc (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:32:102381) at Hc (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:32:102306) at Vc (chrome-extension://fmkadmapgofadopljbjfkapdkoienihi/build/main.js:32:102171)

Component stack: in ec in div in div in div in So in Unknown in n in Unknown in div in div in rl in Ze in fn in Ga in _s

created time in 11 days

pull request commentfacebook/react

useMutableSource: Allow returning function from getSnapshot

@dai-shi's use case of storing a constant function in your store like a state setter (https://github.com/dai-shi/use-context-selector/tree/v2) doesn't seem unreasonable to me, though it's not how I would write the code.

But more I noticed this while reading the code and I don't like things that are ostensibly agnostic to the value you put in them except fail on certain ones for no good reason – I assumed it was an oversight.

sophiebits

comment created time in 12 days

Pull request review commentfacebook/react

useMutableSource: Allow returning function from getSnapshot

 function useMutableSource<Source, Snapshot>(       const latestSetSnapshot = refs.setSnapshot;        try {-        latestSetSnapshot(latestGetSnapshot(source._source));+        const value = latestGetSnapshot(source._source);+        latestSetSnapshot(() => value);          // Record a pending mutable source update with the same expiration time.         const suspenseConfig = requestCurrentSuspenseConfig();

(nb: we still need some wrapper for the exceptions a few lines below this – we could maybe make something different for that to avoid allocating the function in the success case, but… I feel like this is fine?)

sophiebits

comment created time in 13 days

pull request commentfacebook/react

useMutableSource: Allow returning function from getSnapshot

@dai-shi It should.

sophiebits

comment created time in 13 days

PR opened facebook/react

Reviewers
useMutableSource: Allow returning function from getSnapshot

basicStateReducer strikes again.

+43 -2

0 comment

3 changed files

pr created time in 13 days

create barnchsophiebits/react

branch : ums-fn

created branch time in 13 days

PR opened facebook/react

Reviewers
Simplify logic for mutable workInProgressSources

isPrimaryRenderer is always constant for a given React build, so these two arrays do nothing.

+16 -36

0 comment

2 changed files

pr created time in 13 days

create barnchsophiebits/react

branch : simplify-sources

created branch time in 13 days

issue closedfacebook/react

Bug: using useCallback and useEffect at the same time messed my ref

Hey Guys,

I created a SignaturePad for my application that will pass the value later on to Formik. What I'm trying to do is to get the data from canvas and save it to my state using ref. toData() function returns array of points from the signature canvas. handleClear is to clear the canvas.

Related libraries in the project:

		"react": "^16.12.0",
		"react-bootstrap": "1.0.0-beta.16",
		"react-dom": "^16.12.0",
		"@material-ui/core": "^4.9.13",

I'm still new and trying to convert my whole application using hooks so I apologise if this is not a bug.

Problem 1:

I have some issue with using the useEffect and useCallback function of react. Previously before I add useEffect, handleClear function works just fine. However after I added useEffect, sigPad refs always returns null in handleClear.

Problem 2:

I realised after I removed the [sigPad] at handleClear I am able to receive the ref again. Which part of my code re-renders and how come useCallback does not realise that sigPad is changing from null to the correct ref?

Problematic code:

export function Signature() {
  let sigPad = useRef(null);
  const [sig, setSig] = useState("");
  const classes = formStyles();

  useEffect(() => {
    console.log(sigPad);
    setSig(sigPad.toData());
    console.log(sigPad);
  }, [sig]);
  const handleClear = useCallback(() => {
    console.log(sigPad);
    if (sigPad) sigPad.clear();
  }, [sigPad]);

  return (
    <div className="row">
      <Grid spacing={3} container>
        <Grid item xs={12}>
          <h3 className="text-bold">Signature</h3>
        </Grid>
        <Grid item xs={12}>
          <div className="sigCanvas">
            <SignatureCanvas
              penColor="black"
              canvasProps={{ className: "sigPad" }}
              ref={ref => {
                sigPad = ref;
              }}
            />
          </div>
        </Grid>
        <Grid item xs={3}>
          <Button
            variant="contained"
            component="label"
            className={classes.instructions}
            onClick={handleClear}
          >
            Clear
          </Button>
        </Grid>
        <Grid item xs={3}>
          <Button
            component="label"
            variant="contained"
            className={classes.instructions}
          >
            Save
          </Button>
        </Grid>
      </Grid>
    </div>
  );
}

Current Fix:

  const handleClear = useCallback(() => {
    console.log(sigPad);
    if (sigPad) sigPad.clear();
  });

Note: Before I add useEffect I don't have to remove the [sigPad] at my callback

closed time in 13 days

robertwt7

issue commentfacebook/react

Bug: using useCallback and useEffect at the same time messed my ref

You may want to review the useRef docs again. To store data in a ref across renders, you should assign to the .current property (i.e. sigPad.current = ... not sigPad = ...). You likely want just ref={sigPad} on SignatureCanvas which does essentially the same thing. Then read from sigPad.current to get the actual value (in your effect and clear handler).

robertwt7

comment created time in 13 days

issue commentfacebook/create-react-app

Line numbers reported in TypeScript syntax errors can be incorrect

react-scripts 3.4.1 is still latest, so this is still relevant.

sophiebits

comment created time in 21 days

Pull request review commentPyGithub/PyGithub

Improve type signature for create_from_raw_data

 class Github:     def __set_per_page(self, value: int) -> None: ...     def create_from_raw_data(         self,-        klass: Union[Type[Repository], Type[NamedUser]],+        klass: Type[TGithubObject],         raw_data: Dict[str, Any],         headers: Dict[str, Union[str, int]] = ...,-    ) -> Union[Repository, NamedUser]: ...+    ) -> TGithubObject: ...     def dump(self, obj: Repository, file: BytesIO, protocol: int = ...) -> None: ...

I'm not using it in my code so didn't notice, but I suppose so! Update pushed.

sophiebits

comment created time in 22 days

push eventsophiebits/PyGithub

Sophie Alpert

commit sha 99c635d274b6ce8c6043c7e1e00bfe7efdf0d65e

Improve type signature for create_from_raw_data Previously you could call it only on Repository or NamedUser. Now you can call it with any GithubObject subclass -- and the type is carried through to the return value.

view details

push time in 22 days

issue openedfacebook/react

Add devtools "Inspect React component" to right-click menu

Noticed today that Vue's devtools have an awesome "Inspect Vue component" option when right-clicking on a webpage (added in https://github.com/vuejs/vue-devtools/pull/479).

The React devtools should have the same feature! It would be useful when debugging for sure.

created time in 23 days

PR opened PyGithub/PyGithub

Improve type signature for create_from_raw_data

Previously you could call it only on Repository or NamedUser. Now you can call it with any GithubObject subclass -- and the type is carried through to the return value.

FWIW, this is preventing me from upgrading to 1.51.

+6 -4

0 comment

1 changed file

pr created time in 23 days

create barnchsophiebits/PyGithub

branch : cfrd

created branch time in 23 days

fork sophiebits/PyGithub

Typed interactions with the GitHub API v3

https://pygithub.readthedocs.io/

fork in 23 days

PR opened tatianamac/selfdefined

Add "shallow" as possible alternative for "dumb"

eg: This may sound shallow, but I'd really like my next job to have excellent food.

+3 -2

0 comment

1 changed file

pr created time in 25 days

push eventsophiebits/selfdefined

Sophie Alpert

commit sha 765dcf09f5846c30a32eb0972e52ad313fe963ae

Add "shallow" as possible alternative for "dumb" eg: This may sound shallow, but I'd really like my next job to have excellent food.

view details

push time in 25 days

fork sophiebits/selfdefined

Dictionary database with future API and bot integrations

https://www.selfdefined.app/

fork in 25 days

Pull request review commentfacebook/react

[react-refresh/babel] Always insert registrations after var

 export default function(babel, opts = {}) {               return;             }             const handle = createRegistration(programPath, persistentID);-            if (-              (targetExpr.type === 'ArrowFunctionExpression' ||-                targetExpr.type === 'FunctionExpression') &&-              targetPath.parent.type === 'VariableDeclarator'-            ) {-              // Special case when a function would get an inferred name:+            if (targetPath.parent.type === 'VariableDeclarator') {

i.e. you end up with

let Foo = hoc(_c = () => {})
_c2 = Foo;

We could probably do more to preserve the names of inner components too but this should be 95% of the common code patterns.

sophiebits

comment created time in a month

push eventsophiebits/react

Sophie Alpert

commit sha d76d3864bdbdf92c0cea84c89ef05d394f581be2

[react-refresh/babel] Always insert registrations after var Previously, we transformed ``` let Foo = styled.div``; ``` to ``` let Foo = _c1 = styled.div``; ``` and then babel-plugin-styled-components would infer `_c1` as the display name. Widen the existing case that applies to function expressions to apply to any type of variable declaration.

view details

push time in a month

Pull request review commentfacebook/react

[react-refresh/babel] Always insert registrations after var

 export default function(babel, opts = {}) {               return;             }             const handle = createRegistration(programPath, persistentID);-            if (-              (targetExpr.type === 'ArrowFunctionExpression' ||-                targetExpr.type === 'FunctionExpression') &&-              targetPath.parent.type === 'VariableDeclarator'-            ) {-              // Special case when a function would get an inferred name:+            if (targetPath.parent.type === 'VariableDeclarator') {

We add two references for a HOC, one inside and one outside. (findInnerComponents recurses with the same callback.) The else path still applies to the inside one. I'll update the comment.

sophiebits

comment created time in a month

push eventsophiebits/react

Sophie Alpert

commit sha 4cbdcb623237ce12b8001ca8971b8fff95f6624a

[react-refresh/babel] Always insert registrations after var Previously, we transformed ``` let Foo = styled.div``; ``` to ``` let Foo = _c1 = styled.div``; ``` and then babel-plugin-styled-components would infer `_c1` as the display name. Widen the existing case that applies to function expressions to apply to any type of variable declaration.

view details

push time in a month

PR opened facebook/react

Reviewers
[react-refresh/babel] Always insert registrations after var

Previously, we transformed

let Foo = styled.div``;

to

let Foo = _c1 = styled.div``;

and then babel-plugin-styled-components would infer _c1 as the display name. Widen the existing case that applies to function expressions to apply to any type of variable declaration.

+30 -24

0 comment

2 changed files

pr created time in a month

create barnchsophiebits/react

branch : fresh-displayname

created branch time in a month

push eventsophiebits/react-select

Sophie Alpert

commit sha c8447f480f8b9ca04386bee08e8d3a6fbb4f07c8

Rewrite stripDiacritics to be faster We now loop over the string once instead of... 84 times. :) In my tests, this makes rerendering a Select with ~8,000 options about 5x as fast. We could probably make filtering even faster by transforming the search string into a regex that matches the diacritics so we don't have to transform each option, but this alone is a big improvement.

view details

push time in a month

create barnchsophiebits/react-select

branch : diac

created branch time in a month

PR opened JedWatson/react-select

Rewrite stripDiacritics to be faster

We now loop over the string once instead of... 84 times. :)

In my tests, this makes rerendering a Select with ~8,000 options about 5x as fast.

We could probably make filtering even faster by transforming the search string into a regex that matches the diacritics so we don't have to transform each option, but this alone is a big improvement.

+132 -88

0 comment

3 changed files

pr created time in a month

issue commentwhatwg/html

Reparenting iframes without reloading

For what it's worth, from a web dev perspective, there's already a way to ask for an element to be moved in a single step: just call .appendChild or .insertBefore for its new position without ever calling .removeChild. This is in fact what React already does when reordering children within a list.

josepharhar

comment created time in a month

issue commentpmmmwh/react-refresh-webpack-plugin

Module becomes `undefined` after refresh due to cyclic dependencies

Sorry, I had tried on the latest stable but not the latest beta.

For my mini repro case, I did a bisect and it seems that c66bda1da8fe0a13dad7519ca85d8ef6fb8070f8 is the commit that fixed this, though I don't understand why.

But for my larger app, it still seems broken on 0.3.0-beta.5. 🙈 Will try to re-reduce when I have time but lmk if you have other ideas.

sophiebits

comment created time in a month

issue commentpmmmwh/react-refresh-webpack-plugin

Module becomes `undefined` after refresh due to cyclic dependencies

@Timer I think you're the better judge of that! But it does appear that you successfully copied my code into a test case. 😅 Does the fact that it passes CI mean that this works correctly in @next/react-refresh-utils already?

sophiebits

comment created time in a month

issue openedpmmmwh/react-refresh-webpack-plugin

Module becomes `undefined` after refresh due to cyclic dependencies

I'm experiencing a bug where upon changing a file, one of my modules becomes undefined (causing part of the page to disappear).

I've mostly reduced my repro case. It seems related to cyclic dependencies. Repro steps:

  1. Clone https://github.com/sophiebits/refresh-cycle-repro

  2. Run yarn and yarn start, then visit http://localhost:7002/. You'll see the text "Hello: 100".

  3. If you edit the "Hello" (in App.js), it updates properly.

  4. If you edit the "100" (in SurveyOverview.js), the 100 disappears until next refresh.

    This is because the DashboardPage import in routes.js becomes undefined (as you can see from the console logs). If you check the same import a tick later, it is correctly populated.

created time in a month

push eventsophiebits/refresh-cycle-repro

Sophie Alpert

commit sha f898f27918b236749c809ad96459e684b005f925

Initial commit

view details

push time in a month

push eventsophiebits/refresh-cycle-repro

Sophie Alpert

commit sha 648b571781362317897a50da887b666351d0dccf

Initial commit

view details

push time in a month

create barnchsophiebits/refresh-cycle-repro

branch : master

created branch time in a month

created repositorysophiebits/refresh-cycle-repro

created time in a month

pull request commentfacebook/react

Fix mistyped script arbitrary code execution vulnerability

We don't support non-lowercase HTML tags (hence the warning), which is why this wasn't previously changed.

bl00mber

comment created time in a month

pull request commentfacebook/react

Add failing test for #18497

Drawing app. Add a new point every mousemove. This bug means that sometimes you are drawing:

image

And then it adds points in the past and the line jumps around:

image

sophiebits

comment created time in 2 months

pull request commentfacebook/react

Add failing test for #18497

(I thought discrete is only meant for if you need it to be flushed before the next event handler runs.)

sophiebits

comment created time in 2 months

pull request commentfacebook/react

Add failing test for #18497

My understanding of discrete is you effectively lose the concurrency support. The only reason I started using concurrent mode is that I wanted React to automatically batch the renders (more than one mouse move per render). Changing this to be discrete feels like a little bit of a waste.

So it isn't a guarantee that updates at the same priority are processed in order? That's completely contrary to all my past understanding of how concurrent mode works. I thought we subset only based on a priority threshold.

sophiebits

comment created time in 2 months

issue commentfacebook/react

Bug: Concurrent mode processes state updates out of order

Diagnosis in https://github.com/facebook/react/pull/18538#issuecomment-610786771.

sophiebits

comment created time in 2 months

pull request commentfacebook/react

Add failing test for #18497

It looks like this logic is to blame:

https://github.com/facebook/react/blob/2dddd1e00cdadad1783aa55ac65a28634590e9c1/packages/react-reconciler/src/ReactFiberWorkLoop.js#L357-L365

It applies to the "2" update but not "3", causing the "2" update to have a lower priority than the "3" update, which is why we render with only [1,3].

sophiebits

comment created time in 2 months

Pull request review commentfacebook/react

Add failing test for #18497

 describe('ReactHooksWithNoopRenderer', () => {     });     expect(ReactNoop).toMatchRenderedOutput('ABC');   });++  it('keeps intermediate state updates (issue #18497)', () => {+    let _dispatch;+    function Counter() {+      const [list, dispatch] = React.useReducer((l, c) => l.concat([c]), []);+      _dispatch = dispatch;++      const json = JSON.stringify(list);+      Scheduler.unstable_yieldValue('Render ' + json);+      useLayoutEffect(() => {+        Scheduler.unstable_yieldValue('Commit ' + json);+      });++      return json;+    }++    act(() => {+      ReactNoop.render(<Counter />);+      expect(Scheduler).toFlushAndYieldThrough(['Render []', 'Commit []']);+      expect(ReactNoop).toMatchRenderedOutput('[]');+    });++    act(() => {+      _dispatch(1);+      expect(Scheduler).toFlushAndYieldThrough(['Render [1]']);++      _dispatch(2);+      expect(Scheduler).toFlushAndYieldThrough(['Commit [1]']);

Not sure if this is expected either. Should the dispatch prevent this one from being committed? I can't remember how this is supposed to work.

sophiebits

comment created time in 2 months

PR opened facebook/react

Add failing test for #18497
+42 -1

0 comment

2 changed files

pr created time in 2 months

create barnchsophiebits/react

branch : gh-18497-test

created branch time in 2 months

issue commentfacebook/react

Bug? Concurrent mode processes state updates out of order

Same issue with UserBlockingPriority: https://codesandbox.io/s/thirsty-neumann-x1wzx.

sophiebits

comment created time in 2 months

issue commentfacebook/react

Calling window.print() can cause React to crash under specific conditions

@aaqibshehzad Unfortunately there's no easy workaround for applications right now. We need to wait for the Chrome bug to be fixed or add a workaround in React.

However, this only affects the development build of React. So at least it should work correctly in your production builds.

mwszekely

comment created time in 2 months

push eventfacebook/react

Sophie Alpert

commit sha fe2cb525542443aaf1447c4069354c12659fd186

[eslint] Consider `useRef() as ...` as constant (#18496) Sometimes you need to use casts, eg: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/28884#issuecomment-471341041. This change ignores them and allows you to still omit the ref object from the deps list. Test Plan: unit tests

view details

push time in 2 months

PR merged facebook/react

[eslint] Consider `useRef() as ...` as constant CLA Signed

Sometimes you need to use casts, eg: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/28884#issuecomment-471341041. This change ignores them and allows you to omit the ref object from the deps list.

Test Plan: unit tests

+136 -13

5 comments

4 changed files

sophiebits

pr closed time in 2 months

PR opened immerjs/use-immer

useImmerReducer: only call produce() when reducer changes

Previously, this called produce() on every render but discarded the result on every render where reducer didn't change. Now, we use useMemo, which only calls it when reducer changes. (useCallback is really only intended for a function literal first argument.)

+2 -2

0 comment

1 changed file

pr created time in 2 months

push eventsophiebits/use-immer

Sophie Alpert

commit sha 751c448a799b13dca93ebd5eba80c31a3036bb49

useImmerReducer: only call produce() when reducer changes Previously, this called `produce()` on every render but discarded the result on every render where `reducer` didn't change. Now, we use useMemo, which only calls it when `reducer` changes. (useCallback is really only intended for a function literal first argument.)

view details

push time in 2 months

fork sophiebits/use-immer

Use immer to drive state with a React hooks

fork in 2 months

push eventsophiebits/react

Sophie Alpert

commit sha f3920f3d32c796c5e23fb88bb9870490a1b4bafd

[eslint] Consider `useRef() as ...` as constant Sometimes you need to use casts, eg: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/28884#issuecomment-471341041. This change ignores them and allows you to still omit the ref object from the deps list. Test Plan: unit tests

view details

push time in 2 months

Pull request review commentfacebook/react

[eslint] Consider `useRef() as ...` as constant

     "url": "https://github.com/facebook/react/issues"   },   "engines": {-    "node": ">=7"+    "node": ">=10"   },   "homepage": "https://reactjs.org/",   "peerDependencies": {     "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0"+  },+  "dependencies": {

fixed

sophiebits

comment created time in 2 months

issue openedfacebook/react

Bug? Concurrent mode processes state updates out of order

React version: 0.0.0-experimental- d7382b6c4

I have a sandbox that adds the next integer to an array every time you move your mouse: https://codesandbox.io/s/compassionate-currying-nccok.

Intermediate state updates get dropped, then come back later (eg: you would never expect it to render with [0, 2]):

confused

My expectation is that these are all the same priority level and thus get processed in order. Am I doing something wrong?

cc @acdlite @gaearon

created time in 2 months

push eventsophiebits/react

Sophie Alpert

commit sha 3927f36f87879744fb27e69d63ebd8c7f29db9c1

[eslint] Consider `useRef() as ...` as constant Sometimes you need to use casts, eg: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/28884#issuecomment-471341041. This change ignores them and allows you to still omit the ref object from the deps list. Test Plan: unit tests

view details

push time in 2 months

push eventsophiebits/react

Sophie Alpert

commit sha e63ef9f48d39fbc48bae0c872057d98ca238ed4f

[eslint] Consider `useRef() as ...` as constant Sometimes you need to use casts, eg: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/28884#issuecomment-471341041. This change ignores them and allows you to still omit the ref object from the deps list. Test Plan: unit tests

view details

push time in 2 months

PR opened facebook/react

Reviewers
[eslint] Consider `useRef() as ...` as constant

Sometimes you need to use casts, eg: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/28884#issuecomment-471341041. This change ignores them and still allow you to omit the ref object from the deps list.

Test Plan: unit tests

+135 -13

0 comment

4 changed files

pr created time in 2 months

create barnchsophiebits/react

branch : eslint-as

created branch time in 2 months

issue openedfacebook/create-react-app

Line numbers reported in TypeScript syntax errors can be incorrect

Sometimes syntax errors have the wrong line numbers.

Needless to say, this is confusing.

Environment

Environment Info:

  current version of create-react-app: 3.4.1
  running from /Users/sophiebits/.npm/_npx/57068/lib/node_modules/create-react-app

  System:
    OS: macOS High Sierra 10.13.6
    CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
  Binaries:
    Node: 8.12.0 - ~/.nvm/versions/node/v8.12.0/bin/node
    Yarn: 1.16.0 - /usr/local/bin/yarn
    npm: 6.4.1 - ~/.nvm/versions/node/v8.12.0/bin/npm
  Browsers:
    Chrome: 80.0.3987.162
    Firefox: 71.0
    Safari: 13.1
  npmPackages:
    react: ^16.13.1 => 16.13.1 
    react-dom: ^16.13.1 => 16.13.1 
    react-scripts: 3.4.1 => 3.4.1 
  npmGlobalPackages:
    create-react-app: Not Found

Steps to reproduce

<!-- How would you describe your issue to someone who doesn’t know you or your project? Try to write a sequence of steps that anybody can repeat to see the issue. -->

(Write your steps here:)

  1. Run npx create-react-app --template typescript bug
  2. Replace bug/src/App.tsx with the following:
const x = useReducer<A, B>((state, action) => {
  here();
  are();
  some();
  lines();
  to();
  demonstrate();
  the();
  line();
  number();
  can();
  be();
  way();
  off();
  case 'hello':
});

Expected behavior

When loading the project in a browser, expected the error message:

Unexpected token (15:2)

  13 |   way();
  14 |   off();
> 15 |   case 'hello':
     |   ^
  16 | });
  17 | 

Actual behavior

Got the error message:

./src/App.tsx
SyntaxError: /path/to/src/App.tsx: Unexpected token, expected ";" (1:25)

> 1 | const x = useReducer<A, B>((state, action) => {
    |                          ^
  2 |   here();
  3 |   are();
  4 |   some();

NB: yarn tsc does output the right line number in this case, so I don't think it's a TS bug:

$ yarn tsc
src/App.tsx:15:3 - error TS1128: Declaration or statement expected.
15   case 'hello':

Interestingly, the bug goes away if you remove the type param <A, B>.

Reproducible demo

https://github.com/sophiebits/cra-typescript-line-numbers-bug

created time in 2 months

create barnchsophiebits/cra-typescript-line-numbers-bug

branch : master

created branch time in 2 months

created repositorysophiebits/cra-typescript-line-numbers-bug

created time in 2 months

issue commentexcalidraw/excalidraw

Support for writing / rendering math equations

Can it be overlaid instead of drawn in canvas?

avikchaudhuri

comment created time in 2 months

PR opened KaTeX/KaTeX

Fix grammar error in tagline
+2 -2

0 comment

1 changed file

pr created time in 2 months

push eventsophiebits/KaTeX

Sophie Alpert

commit sha 0c398516062a421627d6f119ef34ddd62f7df518

Fix grammar error in tagline

view details

push time in 2 months

issue commentwebpack-contrib/mini-css-extract-plugin

Access Entrypoint Chunk Name At Runtime

It looks as though it's possible to solve this using a variant of what https://github.com/webpack-contrib/worker-loader does – running the entire webpack compiler as a "child" of the main one to produce a bundle that you can reference. I think it's likely possible to make a general purpose version of this but haven't had the time.

philipp-spiess

comment created time in 2 months

issue closedfacebook/react

Include component stack in invariants

IIRC we didn't include it because it was DEV-only. But it's not anymore. Maybe let's start including it?

Errors are often more prominent than warnings, and it would be great to have this info in both.

closed time in 2 months

gaearon

issue commentfacebook/react

Include component stack in invariants

We already log the component stack to the console along with an error (see discussion on #18315). So I don't think there is any action required now. (@gaearon lmk if I'm missing something)

gaearon

comment created time in 2 months

PR closed facebook/react

Include component stack to invariants CLA Signed

close #11619

+43 -19

6 comments

7 changed files

bl00mber

pr closed time in 2 months

pull request commentfacebook/react

Include component stack to invariants

It is interesting that in your screenshot the "The above error" message appears before the actual error. Perhaps related to #18101.

However, given that the stack trace does show up it probably does make sense to leave the behavior as-is. I'll close the original issue too. Sorry to make you spend time on something that didn't end up getting merged, but thank you for the contribution!

bl00mber

comment created time in 2 months

pull request commentfacebook/react

Include component stack to invariants

I was under the impression that we now tack on a component stack to all errors raised during rendering, in a second message that starts "The above error occurred in the <XYZ /> component:". Can you post before and after screenshots of the console?

bl00mber

comment created time in 2 months

issue closedfacebook/react

Bug: react-test-renderer createNodeMock does not seem to work with useRef

<!-- Please provide a clear and concise description of what the bug is. Include screenshots if needed. Please test using the latest version of the relevant React packages to make sure your issue has not already been fixed. -->

React version: 16.9.0 react-test-renderer version: 16.12.0

Steps To Reproduce

  1. Create a functional component that uses useRef
  2. In a test, use createNodeMock to mock the ref when you call renderer.create
  3. Attempt to access .current on your ref
const MyComponent = (): JSX.Element => {
  const myRef = React.useRef<HTMLDivElement>(null);
  console.log('myRef', myRef);

  return <div></div>;
};

export default InfiniteList;

const component = renderer.create(<MyComponent />, {
  createNodeMock() {
    console.log('createNodeMock called');

    return {
      getBoundingClientRect(): { y: number } {
        return {
          y: -1000,
        };
      },
    };
  },
});

The log output is:

  console.log src/components/MyComponent/MyComponent.tsx:62
    myRef { current: null }

  console.log src/components/MyComponent/MyComponent.tsx:110
    createNodeMock called

It's worth noting that this did work within a class component and createRef, but stopped when I converted the component to a functional component that uses useRef.

Link to code example: I was not able to get tests to run on CodeSandbox. <!-- Please provide a CodeSandbox (https://codesandbox.io/s/new), a link to a repository on GitHub, or provide a minimal code example that reproduces the problem. You may provide a screenshot of the application if you think it is relevant to your bug report. Here are some tips for providing a minimal example: https://stackoverflow.com/help/mcve. -->

The current behavior

The .current property on the ref is null

The expected behavior

The .current property on the ref should be the the mock provided by createNodeMock.

closed time in 2 months

mrdanimal

issue commentfacebook/react

Bug: react-test-renderer createNodeMock does not seem to work with useRef

It's hard to tell based on what you've provided, but in general it isn't recommended to read a ref during a render function. Any code that manipulates or measures DOM nodes should be in useEffect, useLayoutEffect, or similar.

I'm guessing that will solve your problem. If not, happy to reopen.

mrdanimal

comment created time in 2 months

issue closedfacebook/react

Bug: Should function isControlled use !== ?

<!-- Please provide a clear and concise description of what the bug is. Include screenshots if needed. Please test using the latest version of the relevant React packages to make sure your issue has not already been fixed. -->

React version: 16.20.0

Steps To Reproduce

  1. inital state is undefined , the useAsyncCustomHooks will call an async function eg: navigator.geolocation.getCurrentPosition
  2. the state will changed later

<!-- Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Issues without reproduction steps or code examples may be immediately closed as not actionable. -->

Link to code example:

  function FC() {
    const [state] = useAsyncCustomHooks()
    return <input  type="text" value={state}/>
  }

<!-- Please provide a CodeSandbox (https://codesandbox.io/s/new), a link to a repository on GitHub, or provide a minimal code example that reproduces the problem. You may provide a screenshot of the application if you think it is relevant to your bug report. Here are some tips for providing a minimal example: https://stackoverflow.com/help/mcve. -->

The current behavior

dev tool throws Warning: A component is changing a controlled input of type hidden to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://fb.me/react-controlled-components

The expected behavior

Not throw that warning, the related source code is: https://github.com/facebook/react/blob/c601f7a64640290af85c9f0e33c78480656b46bc/packages/react-dom/src/client/ReactDOMFiberInput.js#L37-L40

why not !== but != :blush:

closed time in 2 months

xsteadybcgo

issue commentfacebook/react

Bug: Should function isControlled use !== ?

Many applications rely on a value of undefined to mean an uncontrolled component. If you want to treat undefined to mean a controlled empty box, you can always write something like:

<input type="text" value={state === undefined ? '' : state} />

Hope that helps.

xsteadybcgo

comment created time in 2 months

pull request commentfacebook/react

Refactor React.Children to reduce indirection

and is nicer in some ways – eg: count doesn't need to make an array.

gaearon

comment created time in 2 months

pull request commentfacebook/react

Refactor React.Children to reduce indirection

wdyt of just dropping the pooling and closure avoidance but keeping traverseAllChildren with a different callback for map vs forEach vs count? I think that gets you 90% of the code simplification.

gaearon

comment created time in 2 months

PR closed reactjs/reactjs.org

Small updates to versioning policy CLA Signed
+3 -0

3 comments

1 changed file

sophiebits

pr closed time in 3 months

pull request commentreactjs/reactjs.org

Small updates to versioning policy

meh

sophiebits

comment created time in 3 months

issue commentfacebook/react

Expected state to match memoized state before componentDidMount

There's nothing wrong with the code you quoted in isolation, though it would depend what Store.subscribe and onData do.

padlock98

comment created time in 3 months

push eventreactjs/reactjs.org

Luis Filipe

commit sha a9ab627e091be4f13a18c70f4425b347763c4607

Update rendering-elements.md (#2804) Link each mention of a React API in rendering-elements.md to the reference docs. On this page replace every static occurrence of `ReactDOM.render()` by link to the reference docs [`ReactDOM.render()`](/docs/react-dom.html#render) Is this in the right direction @sophiebits ? 🤔 ref #2630

view details

push time in 3 months

PR merged reactjs/reactjs.org

Update rendering-elements.md CLA Signed

Link each mention of a React API in rendering-elements.md to the reference docs.

On this page replace every static occurrence of ReactDOM.render() by link to the reference docs ReactDOM.render()

Is this in the right direction @sophiebits ? 🤔

ref #2630

<!--

Thank you for the PR! Contributors like you keep React awesome!

Please see the Contribution Guide for guidelines:

https://github.com/reactjs/reactjs.org/blob/master/CONTRIBUTING.md

If your PR references an existing issue, please add the issue number below

-->

+4 -4

3 comments

1 changed file

luisFilipePT

pr closed time in 3 months

PR opened facebookexperimental/rome

Fix typo: sparring -> sparing
+1 -1

0 comment

1 changed file

pr created time in 3 months

push eventsophiebits/rome

Sophie Alpert

commit sha 39eb8911a2ea25b749475e018613fc9759ef6712

Fix typo: sparring -> sparing

view details

push time in 3 months

fork sophiebits/rome

An experimental JavaScript toolchain

fork in 3 months

more