profile
viewpoint
Vladimir Kurchatkin vkurchatkin Moscow

vkurchatkin/koa-connect 134

Use connect and express middleware in koa

vkurchatkin/function-origin 50

Get origin of a function in io.js and node.js

vkurchatkin/geojson-flow 9

GeoJSON type declarations for Flow

vkurchatkin/generator-foreach 5

forEach for generators

vkurchatkin/connect-compose 4

Compose connect middleware

vkurchatkin/iojs-ru 1

Перевод io.js на русский язык

vkurchatkin/jquery.couch 1

jquery.couch.js for bower

vkurchatkin/8bit.js 0

8Bit.js Audio Library - Write music using 8bit oscillation sounds.

issue commentfacebook/react

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

The only useful thing that linger could do is just warn is you pass anything other that function expression to useCallback

jdolearydl

comment created time in 7 days

issue commentfacebook/react

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

This is definitely an antipattern. Let's say linter would make you write this:

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

This code is absolute meaningless as it's essentially the same as const callback = cb.

jdolearydl

comment created time in 9 days

issue commentfacebook/react

Question: How to use "useRef" when it is passed through Portal?

Ok, so here are some thoughts. When you want to apply some DOM-base library that's what you usually do (and that's probably what you want to do):

const ref = useRef();

React.useEffect(() => {
  libraryFunction(ref.current);
}, []);

return <div ref={ref}></div>

However, it is only safe to do if you pass the ref to a node that is available right after the component is mounted and until the component is unmounted.

Some examples where it won't work:

return <div>{ foo ? <div ref={ref}/>: null }</div>

div can be mounted later and then remounted multiply times

return <Foobar><div ref={ref}/></Foobar>

Who knows, what Foobar does to it children? Could just pass them through, could render conditionally.

So, if you want to use this pattern, you need to move ref in such a way that is not rendered conditionally and is not wrapped in any custom components that doesn't guarantee to pass through their children unconditionally.

function ModalContent() {
 const ref = useRef();
 // ...
  return <>
       <h3>Test modal</h3>
        <div ref={ref}>Test div with ref prop</div>
    </>
}
krutoo

comment created time in 9 days

issue commentfacebook/react

[eslint-plugin-react-hooks] useReducer purity warning

It's not possible to detect side effects with ESLint:

function reducer() {
   // ...
   let foo = bar(); // does bar trigger an effect? No way to tell
  // ...
}

hug0b

comment created time in 11 days

issue commentfacebook/react

Bug: Complete re-rendering in case of wrapper function

You are right, this is not a bug. When React compares new virtual DOM node with a previous one, first thing it does it checks that the component is the same. If it's not, it unmounts the old one and mounts the new one.

In your case Users component is remounted every time, because it is created inside a component and React sees it as a new component on every render.

Rule of thumb: never create a component inside another component.

borakuldeep

comment created time in 12 days

issue commentfacebook/react

Question: How to use "useRef" when it is passed through Portal?

I mean, are there any more obvious ways to use ref in such cases?

It really depends on what you need to do with the ref

krutoo

comment created time in 14 days

issue commentfacebook/react

Question: How to use "useRef" when it is passed through Portal?

but when modal is shown, ref.current is still undefined.

That is not the case, the ref is fine, you just always log before it is populated

krutoo

comment created time in 14 days

issue commentfacebook/react

Question: How to use "useRef" when it is passed through Portal?

This has nothing to do with portals. Modal is not mounted originally, so the ref is not populated. Also using ref.current as a dependency in useEffect makes no sense, since the component is not rerendered when ref changes.

krutoo

comment created time in 15 days

issue commentfacebook/react

Argument passed to useState hook or value setter method is mutated

Not sure what the problem is here. You mutate value and it gets mutated. Why would you expect anything else?

kcouliba

comment created time in 17 days

issue openedreact-navigation/react-navigation-4

Invalid typing generated for createStackNavigator

Current Behavior

Invalid typing is generated for createStackNavigator, which essentially makes it's return type any:

import { DefaultNavigatorOptions } from '@react-navigation/native';
import { StackRouterOptions } from '@react-navigation/routers';
import { StackNavigationConfig, StackNavigationOptions } from '../types';
declare type Props = DefaultNavigatorOptions<StackNavigationOptions> & StackRouterOptions & StackNavigationConfig;
declare function StackNavigator({ initialRouteName, children, screenOptions, ...rest }: Props): JSX.Element;
declare const _default: <ParamList extends Record<string, object | undefined>>() => import("../../../native/src").TypedNavigator<ParamList, StackNavigationOptions, typeof StackNavigator>;
export default _default;

import("../../../native/src") refers to not existing location

Expected Behavior

Should be import("@react-navigation/native") instead

How to reproduce

N/A

Your Environment

software version
iOS or Android
@react-navigation/native 5.0.0-alpha.25
@react-navigation/stack 5.0.0-alpha.59
react-native-gesture-handler
react-native-safe-area-context
react-native-screens
react-native
expo
node
npm or yarn

created time in 21 days

issue commentfacebook/react

Bug: useReducer runs the queued updates with new props

I’m not 100% sure, but I think that reducer is supposed to be pure, i.e. you can’t use props, otherwise no guarantees are provided

a-c-sreedhar-reddy

comment created time in a month

issue commentfacebook/react

Bug: button onFocus not called when focus() called from useEffect cleanup

It also seems that this is only broken when the effect is unmounting, but works fine when it is updating:

// Helper component to trigger a function when either k changes, or it is unmounted
function OnUnmount({ fn, k }) {
    React.useEffect(() => {
      return () => {
        fn();
      };
    }, [k])

  return null;
}

export default function App() {
  const inputRef = React.useRef();
  const [state, setState] = React.useState(0);

  function run() {
    setState(s => s + 1);
  }

  return (
    <div>
      <button onClick={run}>Run</button>
      <OnUnmount fn={() => {
        inputRef.current.focus();
      }} key={state}/> //
      <input ref={inputRef} onFocus={() => {
        console.log('onFocus');
      }}/>
    </div>
  );
}

In this example the input isn't even focused at all, but if you change key={state} to k={state} it works fine, although there is seemingly no reason for such a discrepancy.

fyodore82

comment created time in a month

issue openedreact-navigation/navigation-ex

Invalid typing generated for createStackNavigator

Current Behavior

Invalid typing is generated for createStackNavigator, which essentially makes it's return type any:

import { DefaultNavigatorOptions } from '@react-navigation/native';
import { StackRouterOptions } from '@react-navigation/routers';
import { StackNavigationConfig, StackNavigationOptions } from '../types';
declare type Props = DefaultNavigatorOptions<StackNavigationOptions> & StackRouterOptions & StackNavigationConfig;
declare function StackNavigator({ initialRouteName, children, screenOptions, ...rest }: Props): JSX.Element;
declare const _default: <ParamList extends Record<string, object | undefined>>() => import("../../../native/src").TypedNavigator<ParamList, StackNavigationOptions, typeof StackNavigator>;
export default _default;

import("../../../native/src") refers to not existing location

Expected Behavior

Should be import("@react-navigation/native") instead

How to reproduce

N/A

Your Environment

software version
iOS or Android
@react-navigation/native 5.0.0-alpha.25
@react-navigation/stack 5.0.0-alpha.59
react-native-gesture-handler
react-native-safe-area-context
react-native-screens
react-native
expo
node
npm or yarn

created time in a month

issue commentfacebook/react

Bug: setState triggers render but doesn't update state

If your long running process is pure computation, then using a web-worker seems to be the best option. In your case it would look something like this:

function runWorker(onStateChange) {
  const source = `
    postMessage("starting");
    let step = 0;
    for (let i = 0; i < 1000000000; i++) {
      if (i % 1000000 === 0) {
        step++;
        postMessage(\`step \${step}\`);
      }
    }
    postMessage("done");
  `;
  const blob = new Blob([source]);
  const url = URL.createObjectURL(blob);
  const worker = new Worker(url);

  worker.onmessage = (e) => {
    onStateChange(e.data)
  }

}

function App() {
  const [state, setState] = useState("");

  return (
    <div>
      <div>State: {state}</div>
      <div>
        <button onClick={() => {
          runWorker(setState)
        }}>Do it with counter</button>
      </div>
    </div>
  );
}

oliversturm

comment created time in 2 months

issue commentfacebook/react

Bug: setState triggers render but doesn't update state

Then set the ref.current.value to be the text you want and set that. I believe that is outside the react tlifecycle and useful for things like timer

No, that won't work either

oliversturm

comment created time in 2 months

issue commentfacebook/react

Bug: setState triggers render but doesn't update state

Promises are interesting this way: then callbacks are executed asynchronously but they still prevent browser logic from running. It goes like this:

|---- synchronous JS running ----|---- promise callbacks running ----|---- browser repaints ---- |

So, for example, this blocks the browser just the same:

let i = 0;
function update() {
  rootElement.innerHTML = 'c ' + i;
  i++;

  Promise.resolve().then(update);
}

update();

While this works fine:

let i = 0;
function update() {
  rootElement.innerHTML = 'c ' + i;
  i++;

  setTimeout(update, 0)
}

update();
oliversturm

comment created time in 2 months

issue commentfacebook/react

Bug: setState triggers render but doesn't update state

@JKCooper2 is right, it has nothing to do with React. You just can't report the progress of a synchronous computation. You need to break into pieces by calling setTimeout(0) or something similar.

So my issue remains the same: there doesn't seem to be a reason to call the render logic if the state change that triggers it has not actually been applied.

React calls render logic synchronously when you call setState. It is ready to update the DOM after that, but it just doesn't have the chance until the loop is over.

oliversturm

comment created time in 2 months

issue closedracer-rust/racer

No autocompletion for arguments of async functions

I'm using rls 1.40.0 (5db91c7 2019-10-30) with vscode. I get not autocompletion for s in this code:

async fn test(s: &str) {
}

If I alias s with and explicit annotation, it works fine:

async fn test(s: &str) {
    let s: &str = s;
}

closed time in 2 months

vkurchatkin

issue commentracer-rust/racer

No autocompletion for arguments of async functions

Works fine on nightly, so probably already fixed

vkurchatkin

comment created time in 2 months

issue openedracer-rust/racer

No autocompletion for arguments of async functions

I'm using rls 1.40.0 (5db91c7 2019-10-30) with vscode. I get not autocompletion for s in this code:

async fn test(s: &str) {
}

If I alias s with and explicit annotation, it works fine:

async fn test(s: &str) {
    let s: &str = s;
}

created time in 2 months

issue commentfacebook/react

[Hooks] useEffect is behaving little odd

You can't really observe current props in react that way, they are essentially immutable. It can be done like this:

function Component({ prop }) {
  const propRef = React.useRef();
  propRef.current = prop;

   React.useEffect(() => {
      setTimeout(() => {
         console.log(propRef.current) // always get the prop from the most recent render
      }, 1000);
   }, []);
}
ssahaxd

comment created time in 2 months

issue commentfacebook/react

why not the useMemo memory Multiple value

so why not provide a another hook to let developer choise between minimize the memory or optimization of time?

You can do it! But would be probably be too opinionated to be included in React itself. Something like this could work for you:

function useMyMemo(fn, deps) {
  const cacheRef = React.useRef();

  if (!cacheRef.current) {
      cacheRef.current = new MyCoolCache();
   }

  const cachedValue = cacheRef.current.get(deps);

  if (cachedValue !== undefined) {
    return cachedValue;
  }

 const value = fn();
 cacheRef.current.set(deps, value);
 return value;
}
zhangenming

comment created time in 2 months

issue commentfacebook/react

why not the useMemo/useCallback Multiple Memory

@zhangenming useMemo caches only the most recent value, not all observed values

zhangenming

comment created time in 2 months

issue commentfacebook/react

Props, hooks, and re-rendering

Such a hook seems like a very bad idea. Essentially, it creates a loop in your data flow which tends to lead to all kinds of bugs. From what I've seen, there is always a better solution for cases where one might use something like this.

elliotcm

comment created time in 2 months

issue commentfacebook/react

Cant use name starting with use in the React Hooks' function Name.

You shouldn’t be doing that. Names starting with use are reserved for hooks.

durgeshsatyam

comment created time in 2 months

issue commentfacebook/react

useEffect and useState infinite loop inconsistencies

This works as expected. Not sure what you are trying to do, but this:

 const a = {};
  React.useEffect(() => {
    // ...
  }, [a])

is essentially the same as omitting dependencies altogether, as a is going to be different on each render.

joy-void-joy

comment created time in 2 months

issue commentfacebook/react

Pass hook functions as third parameter

The question is, why would you want components to be pure functions? Is there any practical reason?

akmjenkins

comment created time in 2 months

issue commentnodejs/node

Promise.all() dies silently if no resolve

I think this should be closed. The promise that never resolves can't possible affect the program. If node exits, that means that all pending promises could never be resolved, because there is noting going on with the event loop. In fact, such promises might be even garbage collected at this point. Indeed, promises just represent callbacks, not some pending processes that should keep node process alive.

acenturyandabit

comment created time in 2 months

issue commentfacebook/react

Pattern for "onchange" callbacks

eslint forces me to also insert the onchange-method given from props to the dependencies.

It actually doesn't. You are free to ignore the warning, if you are sure that's what you want to do

LeopoldLerch

comment created time in 2 months

issue commentfacebook/react

Support rendering into comment

Is there some particular use case for this feature?

dawidgarus

comment created time in 3 months

issue commentfacebook/react

useState hook behaves differently than setState when setting a Component in the state

Thats because your component is actually a function, and passing a function to a useState setter has different meaning:

const [val, setVal] = React.useState();

setVal({ foo: 123 }); // val will be { foo: 123} on next render

setVal(() => 123); // val will be 123, not () => 123 on next render

To side step this behaviour you can pass a function that returns a function instead:

setVal(() => () => 123); // now it's going to be () => 123 on next render

Applying this concept to your example:

const AsyncComponent = props => {
  const [LoadedComponent, setLoadedComponent] = useState(null);
  const { loadComponent } = props;

  useEffect(() => {
    if (!LoadedComponent) {
      loadComponent().then(Component => {
        setLoadedComponent(() => Component.default ? Component.default : Component);          // <--- HERE: that's it, just add () => 
      });
    }
  }, []);

  console.log(LoadedComponent); // {type: "div", key: null,ref: null,props: Object,_owner: null,_store: Object}

  return (
    <Fragment>
      {LoadedComponent ? <LoadedComponent /> : <LoadingIndicator />}
    </Fragment>
  );
};
AnupamaHosad

comment created time in 3 months

issue commentfacebook/react

[Q] How to perform a server side data fetching with React Hooks

Essentially, you have to implement a custom hook that is capable of reading data from cache:

function useData(url) {
  let [, setDummy] = React.useState(false);

  React.useEffect(() => {
    cache.fetch(url).then(() => { setDummy(val => !val) });
  }, [url]);

  return cache.get(url);
}

When you have something like this in place, on your server you need to populate your cache with relevant data before rendering:

await Promise.all([cache.fetch(url1), cache.fetch(url2)]);

Then you need to serialize your cache and send to the browser, so your app could be hydrated properly.

idangozlan

comment created time in 3 months

issue commentfacebook/react

Reordering of list's items leads to scroll to the top of page on Android device

This doesn't really have anything to do with React. To reorder existing DOM nodes React has to remove the from DOM, which messes up with the scroll.

arhontmw

comment created time in 3 months

issue commentfacebook/react

Triggering suspense with rejected promise causes re-render instead of error boundary

It seems that this is actually the intended behaviour. See example from the docs: https://codesandbox.io/s/adoring-goodall-8wbn7

Basically, if you want to handle data fetching error with an ErrorBoundary, you need to throw the error synchronously on subsequent rerender. This is what the example does:

function wrapPromise(promise) {
  let status = "pending";
  let result;
  let suspender = promise.then(
    r => {
      status = "success";
      result = r;
    },
    e => {
      status = "error";
      result = e;
    }
  );
  return {
    read() {
      if (status === "pending") {
        throw suspender;
      } else if (status === "error") {
        throw result;
      } else if (status === "success") {
        return result;
      }
    }
  };
}

Worth noting that the example explicitly says not to copy-paste this code

joeldenning

comment created time in 3 months

issue commentfacebook/react

react-dom logs error to console when form.checkValidity() is called during render

You are not supposed to touch DOM in render. Something like this might work for your case:

  const [isValid, setIsValid] = useState(false); 
  // ...
  return (
    <form onSubmit={e => e.preventDefault()} ref={formRef} onChange={() => { setIsValid(formRef.current.checkValidity()) }}>

// ...
nwoltman

comment created time in 3 months

issue commentfacebook/react

Passing in prop equality fn to React.memo can reset state from Hooks during updates

A correct implementation should at least perform a shallow equality check for all props. In your case you don't need a comparator at all, you need to make your increment function stable. That is usually performed by useCallback:

const increment = useCallback(function increment(key) {
    const nextState = [...state];
    nextState[key]++;
    setState(nextState);
  }, [state]);

Unfortunately, this won't really do any good, since it closes over state and will be update on each state change anyway. The best way to avoid it is use indeed to pass a function to setState:

const increment = useCallback(function increment(key) {
    setState(state => {
        const nextState = [...state];
        nextState[key]++;
        return nextState;
    });
  }, []);

This way you can drop state from the dependencies. You can implement the same concept with useReducer as well. Another trick is to use useRef (although I wouldn't recommend it):

  const incrementRef = React.useRef();
  incrementRef.current = (key) => {
    const nextState = [...state];
    nextState[key]++;
    setState(nextState);
  }


  const increment = React.useCallback(function increment(key) {
    incrementRef.current(key);
  }, []);
eshifrin

comment created time in 3 months

issue commentfacebook/react

Passing in prop equality fn to React.memo can reset state from Hooks during updates

Well, you've implemented comparator incorrectly, so this is expected. Your component is not rendered when increment is changed, hence this behaviour.

eshifrin

comment created time in 3 months

issue commentfacebook/react

React forces component to un-mount and mount when it should only update it

In my case the type does not change.the reference may have changed.

That is exactly the problem. How does react know whether the type is the same or not? It just compares components by reference.

amazzalel-habib

comment created time in 3 months

push eventvkurchatkin/typescript-vs-flow

Vladimir Kurchatkin

commit sha d02d421850ca72744ef5d6207df1588ce1c28397

Update README.md

view details

push time in 4 months

issue commentfacebook/react

Effect is not run (not even once) when state setter is called in function body

That's because you call setState synchronously in you render, which basically tells that your current render should be discarded, including effects.

charshin

comment created time in 4 months

issue commentfacebook/react

Unable to render nested <optgroup> elements in a <select>

You are not really allowed to nest optgroup in another optgroup

theetrain

comment created time in 4 months

issue commentfacebook/react

Feature request: useRender()

Where in the tree is this element supposed to be rendered?

adrianhelvik

comment created time in 4 months

issue commentfacebook/react

Misleading (?) wording in documentation

So a custom hook might as well not call any other hooks.

Yes, that is true, and it will still be a hook. When you say that a function is a hook, it means that the user of this function must follow the rules of hooks, no matter what the implementation currently is.

For example, you can do this:

function useCurrentUser() {
  return {
     username: 'Foo'
  };
}

And then swap it for the actual implementation without breaking possible callers:

function useCurrentUser() {
  return useContext(UserContext);
}
brunoscopelliti

comment created time in 4 months

issue commentfacebook/react

useEffect callback never called

Here is somewhat minimal reproduction:

function useTest() {
  const [effect, setEffect] = useState(false);
  useEffect(() => {
    setEffect(true);
  }, []);

  return effect;
}

function A() {
  const effect = useTest();

  return (
    <div >
      {"" + effect}
      {effect && <B/>}
    </div>
  );
}

function B() {
  const effect = useTest();

  return (
    <div >
      {"" + effect}
      {effect && <C/>}
    </div>
  );
}


function C() {
  const effect = useTest();

  return (
    <div >
      {"" + effect}
    </div>
  );
}

function Other() {
  useEffect(() => {}, []);
  return null;
}


ReactDOM.render(
  <A/>,
  document.querySelector("#root1")
);

ReactDOM.render(
  <Other/>,
  document.querySelector("#root2")
);
pschiffmann

comment created time in 5 months

issue commentfacebook/react

React hooks in HOC

Yes, this is fine. Higher-order components are not components, but if you return a function component from a HOC, you can use hooks their. So, your example is fine, but this is not:

const withMutation = gql => C => {
   const [onSubmit, {data}] = useMutation (SIGNUP_GQL); // <-- outside of the component

   return props => {
     return <C onSubmit={onSubmit} data={data} />
  };
}
dteiml

comment created time in 5 months

issue commentfacebook/react

React functional component is taking snapshot of state at the time of registering handler on websocket

This is what is called a "stale closure". You can read more about this here: https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function

If you want to access most recent state in your closure, you can use refs:

const [val, setVal] = React.useState('');
const ref = useRef(val);

React.useEffect(() => {
  ref.current = val;
}, [val]);

function myClosure() {
   const currentVal = ref.current;
  // ....
}

sidvanarse

comment created time in 5 months

issue commentfacebook/react

Redundant re-rendering even though setting the same state (with useState hook)

This is actually documentede here: https://reactjs.org/docs/hooks-reference.html#usestate

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because React won’t unnecessarily go “deeper” into the tree.

adamkleingit

comment created time in 5 months

issue commentfacebook/react

Calling setState in the callback of setState prevents input's value to be updated by onChange

is not intuitive for react devs, violates react rules.

Can you elaborate? What rules does this violate?

adriendomoison

comment created time in 6 months

more