New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: React Hooks #68

Open
wants to merge 2 commits into
base: master
from

Conversation

Projects
None yet
@sebmarkbage
Collaborator

sebmarkbage commented Oct 25, 2018 •

In this RFC, we propose introducing Hooks to React. See the RFC and the documentation for more details.

https://reactjs.org/docs/hooks-overview.html

View formatted RFC

(The talk video has now been published too.)

RFC: React Hooks
In this RFC, we propose introducing *Hooks* to React. See the RFC and the documentation for more details.

https://reactjs.org/docs/hooks-overview.html
@grabbou

This comment has been minimized.

Show comment
Hide comment
@grabbou

grabbou Oct 25, 2018

Question about persisting values of useState - is the preferred way to create a custom usePersistedState hook that calls into storage mechanism?

I was wondering if there was a way to batch the write operations in environments such as React Native and how did you approach that problem at Facebook during your initial adoption?

grabbou commented Oct 25, 2018

Question about persisting values of useState - is the preferred way to create a custom usePersistedState hook that calls into storage mechanism?

I was wondering if there was a way to batch the write operations in environments such as React Native and how did you approach that problem at Facebook during your initial adoption?

@pcmaffey

This comment has been minimized.

Show comment
Hide comment
@pcmaffey

pcmaffey Oct 25, 2018

Is this the right place for feedback? First of all - amazing work. I love where this is going with composability. My big question is about performance of Hooks.

Are all these function hooks redefined and recalled on every render?

pcmaffey commented Oct 25, 2018

Is this the right place for feedback? First of all - amazing work. I love where this is going with composability. My big question is about performance of Hooks.

Are all these function hooks redefined and recalled on every render?

@pheuter

This comment has been minimized.

Show comment
Hide comment
@pheuter

pheuter Oct 25, 2018

Just watched the React Conf keynote, awesome presentation, super excited to give hooks a shot!

Not sure if this is the right place to ask but was wondering how function components that make use of hooks affect server-side rendering. In useEffects() for example, will errors be thrown when accessing browser apis like window during ssr?

pheuter commented Oct 25, 2018

Just watched the React Conf keynote, awesome presentation, super excited to give hooks a shot!

Not sure if this is the right place to ask but was wondering how function components that make use of hooks affect server-side rendering. In useEffects() for example, will errors be thrown when accessing browser apis like window during ssr?

@pheuter

This comment has been minimized.

Show comment
Hide comment
@pheuter

pheuter Oct 25, 2018

@pcmaffey Looks like this FAQ entry addresses your performance concern.

pheuter commented Oct 25, 2018

@pcmaffey Looks like this FAQ entry addresses your performance concern.

@JoshuaKGoldberg

This comment has been minimized.

Show comment
Hide comment
@JoshuaKGoldberg

JoshuaKGoldberg Oct 25, 2018

Very exciting, this looks awesome!

Questioning the tuple return type:

const [count, setCount] = useState(0);

Why an array tuple instead of an object containing count and setCount members? Is this for performance (and if so, do we have numbers to show browsers or Node behaving strongly differently)? It feels like leaving the returned object open to adding more fields might make it easier to remain backwards compatible in the future, similar to how APIs often end up taking in single objects as a parameter rather than long lists of parameters.

const { value, set } = useState(0);

Edit: yes, per @jaredLunde's comment, the properties would need constant names.

JoshuaKGoldberg commented Oct 25, 2018 •

Very exciting, this looks awesome!

Questioning the tuple return type:

const [count, setCount] = useState(0);

Why an array tuple instead of an object containing count and setCount members? Is this for performance (and if so, do we have numbers to show browsers or Node behaving strongly differently)? It feels like leaving the returned object open to adding more fields might make it easier to remain backwards compatible in the future, similar to how APIs often end up taking in single objects as a parameter rather than long lists of parameters.

const { value, set } = useState(0);

Edit: yes, per @jaredLunde's comment, the properties would need constant names.

@jaredLunde

This comment has been minimized.

Show comment
Hide comment
@jaredLunde

jaredLunde Oct 25, 2018

@JoshuaKGoldberg How would you customize those object properties? Array is the cleanest way it works with custom naming.

jaredLunde commented Oct 25, 2018 •

@JoshuaKGoldberg How would you customize those object properties? Array is the cleanest way it works with custom naming.

@alexeyraspopov

This comment has been minimized.

Show comment
Hide comment
@alexeyraspopov

alexeyraspopov Oct 25, 2018

Why an array tuple instead of an object containing count and setCount members?

You can assign names you need. Object destructuring requires you to put specific keys. You may end up having something like

let { state: name, setState: setName } = useState('Name');
let { state: surname, setState: setSurname } = useState('Surname');

Which is not the case with tuples.

alexeyraspopov commented Oct 25, 2018 •

Why an array tuple instead of an object containing count and setCount members?

You can assign names you need. Object destructuring requires you to put specific keys. You may end up having something like

let { state: name, setState: setName } = useState('Name');
let { state: surname, setState: setSurname } = useState('Surname');

Which is not the case with tuples.

@jamesplease

This comment has been minimized.

Show comment
Hide comment
@jamesplease

jamesplease Oct 25, 2018

I'm still familiarizing myself with this API, but I'm optimistic about these changes. Great work, React team!

My main concern with hooks is related to the learning curve. There are some APIs introduced that new (and seasoned) developers may not immediately pick up on.

One in particular that stands out the most to me is useEffect(myEffect, []). It's not very expressive. For those who haven't read the docs, what do you think this does? I'd be surprised if someone could guess.

For those who are still familiarizing themselves with the API, it calls the effect only on mounting and unmounting, and not on updates (docs here).

I know that this proposal introduces a lot of new functions, but it might be worthwhile adding another one that functions the same as useEffect(myEffect, []). As for the name? I'm not sure. Perhaps something like useMountEffect()?

jamesplease commented Oct 25, 2018 •

I'm still familiarizing myself with this API, but I'm optimistic about these changes. Great work, React team!

My main concern with hooks is related to the learning curve. There are some APIs introduced that new (and seasoned) developers may not immediately pick up on.

One in particular that stands out the most to me is useEffect(myEffect, []). It's not very expressive. For those who haven't read the docs, what do you think this does? I'd be surprised if someone could guess.

For those who are still familiarizing themselves with the API, it calls the effect only on mounting and unmounting, and not on updates (docs here).

I know that this proposal introduces a lot of new functions, but it might be worthwhile adding another one that functions the same as useEffect(myEffect, []). As for the name? I'm not sure. Perhaps something like useMountEffect()?

@eps1lon

This comment has been minimized.

Show comment
Hide comment
@eps1lon

eps1lon Oct 25, 2018

It is a very early time for Hooks, so some integrations like DevTools support or Flow/TypeScript typings may not be ready yet.

Will I be able to inspect what hooks a component is using?

Having an object with named properties as state made it easy to see what's what. I guess this will be hard with the new useState?

eps1lon commented Oct 25, 2018

It is a very early time for Hooks, so some integrations like DevTools support or Flow/TypeScript typings may not be ready yet.

Will I be able to inspect what hooks a component is using?

Having an object with named properties as state made it easy to see what's what. I guess this will be hard with the new useState?

@benjamn

This comment has been minimized.

Show comment
Hide comment
@benjamn

benjamn Oct 25, 2018

@eps1lon According to the FAQ, useState is backed by a list of anonymous memory cells:

There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

So if you ever find yourself trying to debug the underlying state, you're probably going to be working with a linked list of unnamed values. To figure out which memory cell is which, you'll have to refer back to the order of your useState calls.

Full disclosure: I'm planning to open an issue today to discuss a system for providing meaningful names for your useState calls, which should significantly relax the current usage restrictions, and eliminate the need for a linter to enforce those rules.

benjamn commented Oct 25, 2018

@eps1lon According to the FAQ, useState is backed by a list of anonymous memory cells:

There is an internal list of “memory cells” associated with each component. They’re just JavaScript objects where we can put some data. When you call a Hook like useState(), it reads the current cell (or initializes it during the first render), and then moves the pointer to the next one. This is how multiple useState() calls each get independent local state.

So if you ever find yourself trying to debug the underlying state, you're probably going to be working with a linked list of unnamed values. To figure out which memory cell is which, you'll have to refer back to the order of your useState calls.

Full disclosure: I'm planning to open an issue today to discuss a system for providing meaningful names for your useState calls, which should significantly relax the current usage restrictions, and eliminate the need for a linter to enforce those rules.

@spicydonuts

This comment has been minimized.

Show comment
Hide comment
@spicydonuts

spicydonuts Oct 25, 2018

Positional effects (using any of these use* functions is an effect, even just to read state) worry me. It seems easy to get wrong, and doing so might not present until production. For the same reason it also seems like it'll be extremely difficult to introduce to beginners -- "the magic function works here but not there".

Using Symbols instead of positional keys would make it easier to understand and harder to get wrong:

const $count = Symbol("count");

function MyComponent() {
  const [count, setCount] = useState($count, 0);
  ...
}

Edit for clarification: I don't mean to say the Symbol would be a global key -- it would still use the current context (the Fiber, I assume) as the primary key and the Symbol as the secondary key (where the effectful call order is currently being used).

spicydonuts commented Oct 25, 2018 •

Positional effects (using any of these use* functions is an effect, even just to read state) worry me. It seems easy to get wrong, and doing so might not present until production. For the same reason it also seems like it'll be extremely difficult to introduce to beginners -- "the magic function works here but not there".

Using Symbols instead of positional keys would make it easier to understand and harder to get wrong:

const $count = Symbol("count");

function MyComponent() {
  const [count, setCount] = useState($count, 0);
  ...
}

Edit for clarification: I don't mean to say the Symbol would be a global key -- it would still use the current context (the Fiber, I assume) as the primary key and the Symbol as the secondary key (where the effectful call order is currently being used).

@adamhaile

This comment has been minimized.

Show comment
Hide comment
@adamhaile

adamhaile Oct 25, 2018

Just curious, are React hooks at all inspired by S and Surplus? There are similarities down to even the names and terminology used. S has S.effect() and S.cleanup(), and useState() is analogous to S's S.data().

For instance, here's the hooks example in Surplus:

function Example() {
  const count = S.data(0); // S.data instead of React.useState

  S.effect(() => { // S.effect instead of React.useEffect
    document.title = `You clicked ${count()} times`;
  });

  return (
    <div>
      <p>You clicked {count()} times</p>
      <button onClick={() => count(count() + 1)}>
        Click me
      </button>
    </div>
  );
}

In fact, I used almost this exact same example in the Surplus FAQ to explain how functional components could have state -- the very same issue hooks are solving for React.

I'm the author of S and Surplus, and reading the hook docs gave me a strong case of déjà vu! The similarities may be coincidental -- we're probably reading the same upstream sources. But if there was any influence, I thought that would be cool :).

adamhaile commented Oct 25, 2018

Just curious, are React hooks at all inspired by S and Surplus? There are similarities down to even the names and terminology used. S has S.effect() and S.cleanup(), and useState() is analogous to S's S.data().

For instance, here's the hooks example in Surplus:

function Example() {
  const count = S.data(0); // S.data instead of React.useState

  S.effect(() => { // S.effect instead of React.useEffect
    document.title = `You clicked ${count()} times`;
  });

  return (
    <div>
      <p>You clicked {count()} times</p>
      <button onClick={() => count(count() + 1)}>
        Click me
      </button>
    </div>
  );
}

In fact, I used almost this exact same example in the Surplus FAQ to explain how functional components could have state -- the very same issue hooks are solving for React.

I'm the author of S and Surplus, and reading the hook docs gave me a strong case of déjà vu! The similarities may be coincidental -- we're probably reading the same upstream sources. But if there was any influence, I thought that would be cool :).

@alexeyraspopov

This comment has been minimized.

Show comment
Hide comment
@alexeyraspopov

alexeyraspopov Oct 25, 2018

@alqamabinsadiq, sorry if my comment was somehow confusing. This is not how the hook intended to be used, I was making an example of additional effort required for using object destructuring. This is how the correct code looks like:

let [name, setName] = useState('Name');
let [surname, setSurname] = useState('Surname');

Less effort to write, less effort to read.

alexeyraspopov commented Oct 25, 2018 •

@alqamabinsadiq, sorry if my comment was somehow confusing. This is not how the hook intended to be used, I was making an example of additional effort required for using object destructuring. This is how the correct code looks like:

let [name, setName] = useState('Name');
let [surname, setSurname] = useState('Surname');

Less effort to write, less effort to read.

@sophiebits

This comment has been minimized.

Show comment
Hide comment
@sophiebits

sophiebits Oct 25, 2018

Member

@adamhaile To my knowledge we weren’t influenced at all by Surplus (this is my first time seeing it). It’s true the “effect” name is similar, but both names are descriptive, so I guess it shouldn’t be too surprising that the names overlap.

Member

sophiebits commented Oct 25, 2018

@adamhaile To my knowledge we weren’t influenced at all by Surplus (this is my first time seeing it). It’s true the “effect” name is similar, but both names are descriptive, so I guess it shouldn’t be too surprising that the names overlap.

@sebmarkbage

This comment has been minimized.

Show comment
Hide comment
@sebmarkbage

sebmarkbage Oct 25, 2018

Collaborator

@benjamn @spicydonuts If you decide to publish a follow up RFC with named hooks which doesn’t have the conditionality constraints, then be sure to cover other pitfalls that you may also get. In the current proposal there is clearly one thing that will unexpectedly break when you don’t have names. However there are other things that might become confusing too. Such as that an effect doesn’t cleanup and refire when it’s in a conditional. So even with names you might find it best practice to avoid conditionals.

Collaborator

sebmarkbage commented Oct 25, 2018

@benjamn @spicydonuts If you decide to publish a follow up RFC with named hooks which doesn’t have the conditionality constraints, then be sure to cover other pitfalls that you may also get. In the current proposal there is clearly one thing that will unexpectedly break when you don’t have names. However there are other things that might become confusing too. Such as that an effect doesn’t cleanup and refire when it’s in a conditional. So even with names you might find it best practice to avoid conditionals.

@spicydonuts

This comment has been minimized.

Show comment
Hide comment
@spicydonuts

spicydonuts Oct 25, 2018

I see what you mean. Hmm.. that's unfortunate 🤔

spicydonuts commented Oct 25, 2018

I see what you mean. Hmm.. that's unfortunate 🤔

@rudolfolah

This comment has been minimized.

Show comment
Hide comment
@rudolfolah

rudolfolah Oct 25, 2018

I like the idea, but I think the naming doesn't really reflect what's going on here. The term hook in other contexts, such as web hooks or Emacs, implies that something happens at a particular point in time and calls out to some other functions/methods to make it happen.

In the words of the Github docs for Web hooks:

Webhooks allow you to build or set up GitHub Apps which subscribe to certain events on GitHub.com. When one of those events is triggered, we'll send a HTTP POST payload to the webhook's configured URL.

For example web hooks are called whenever Github detects a branch has been created. They're called in Emacs whenever a file is loaded or a particular mode (for syntax highlighting + shortcuts) is activated.

In React, the only hooks I can think of at the moment are the componentDidMount and componentWillUnmount functions, since they're part of a lifecycle and call out to some other function (as part of being overridden in a Component class)

From the React Hooks documentation it looks like these are managers:

  • useState manages and coordinates state
  • useEffect manages and supervises side-effects
  • useContext manages context

Other options for naming:

  • manager
  • supervisor
  • coordinator
  • handler

I'm sure there are other, better names other than "hook" which can be used.

Also, the naming of the methods don't need to change since none of them seem to have the word "hook" in them, the naming change would just affect the rest of the documentation/examples.

rudolfolah commented Oct 25, 2018

I like the idea, but I think the naming doesn't really reflect what's going on here. The term hook in other contexts, such as web hooks or Emacs, implies that something happens at a particular point in time and calls out to some other functions/methods to make it happen.

In the words of the Github docs for Web hooks:

Webhooks allow you to build or set up GitHub Apps which subscribe to certain events on GitHub.com. When one of those events is triggered, we'll send a HTTP POST payload to the webhook's configured URL.

For example web hooks are called whenever Github detects a branch has been created. They're called in Emacs whenever a file is loaded or a particular mode (for syntax highlighting + shortcuts) is activated.

In React, the only hooks I can think of at the moment are the componentDidMount and componentWillUnmount functions, since they're part of a lifecycle and call out to some other function (as part of being overridden in a Component class)

From the React Hooks documentation it looks like these are managers:

  • useState manages and coordinates state
  • useEffect manages and supervises side-effects
  • useContext manages context

Other options for naming:

  • manager
  • supervisor
  • coordinator
  • handler

I'm sure there are other, better names other than "hook" which can be used.

Also, the naming of the methods don't need to change since none of them seem to have the word "hook" in them, the naming change would just affect the rest of the documentation/examples.

@leebyron

This comment has been minimized.

Show comment
Hide comment
@leebyron

leebyron Oct 25, 2018

Loving this new API, but I have one primary concern - where the hooks come from.

I'm concerned that these hook functions are provided by the top level react module and imply (or require) global state to work. Ideally, hooks and effects functions could be provided to the functional component when it's executed.

So while this example as illustrated by Dan requires from the module:

const { useContext } = require('react')
const SomeContext = require('./SomeContext)

function Example({ someProp }) {
  const contextValue = useContext(SomeContext)
  return <div>{someProp}{contextValue}</div>
}

Was it considered to pass the hooks into the functional component?

Perhaps looking something like:

const SomeContext = require('./SomeContext)

function Example({ someProp }, hooks) {
  const contextValue = hooks.useContext(SomeContext)
  return <div>{someProp}{contextValue}</div>
}

This means functional components which use hooks are (Props, Hooks) => ReactNode. While this is still not "pure" because hooks have effects and are not pure, at least the renderer could provide the appropriate hooks per call-site instead of relying on global state. I could imagine that the Fiber renderer might have different implementation of hooks than some potential future renderer, a server-side renderer, a test renderer with mocked effects, etc.

Thoughts?

leebyron commented Oct 25, 2018

Loving this new API, but I have one primary concern - where the hooks come from.

I'm concerned that these hook functions are provided by the top level react module and imply (or require) global state to work. Ideally, hooks and effects functions could be provided to the functional component when it's executed.

So while this example as illustrated by Dan requires from the module:

const { useContext } = require('react')
const SomeContext = require('./SomeContext)

function Example({ someProp }) {
  const contextValue = useContext(SomeContext)
  return <div>{someProp}{contextValue}</div>
}

Was it considered to pass the hooks into the functional component?

Perhaps looking something like:

const SomeContext = require('./SomeContext)

function Example({ someProp }, hooks) {
  const contextValue = hooks.useContext(SomeContext)
  return <div>{someProp}{contextValue}</div>
}

This means functional components which use hooks are (Props, Hooks) => ReactNode. While this is still not "pure" because hooks have effects and are not pure, at least the renderer could provide the appropriate hooks per call-site instead of relying on global state. I could imagine that the Fiber renderer might have different implementation of hooks than some potential future renderer, a server-side renderer, a test renderer with mocked effects, etc.

Thoughts?

@KARTIK01

This comment has been minimized.

Show comment
Hide comment
@KARTIK01

KARTIK01 Oct 25, 2018

for new react developers, useState hooks will be a magic.

KARTIK01 commented Oct 25, 2018

for new react developers, useState hooks will be a magic.

@ntucker

This comment has been minimized.

Show comment
Hide comment
@ntucker

ntucker Oct 25, 2018

How does this interact with React.memo()? Does it just shallow check props and ignore state and context. If not, how does it know what state and context to check?

ntucker commented Oct 25, 2018

How does this interact with React.memo()? Does it just shallow check props and ignore state and context. If not, how does it know what state and context to check?

@alexeyraspopov

This comment has been minimized.

Show comment
Hide comment
@alexeyraspopov

alexeyraspopov Oct 25, 2018

I'm concerned that these hook functions are provided by the top level react module and imply (or require) global state to work. Ideally, hooks and effects functions could be provided to the functional component when it's executed.

@leebyron, I think, the way how it works, is by using an incapsulated access to the current rendering fiber that holds the state and effects. The API may look like something "global" happens under the hood, but it is still scoped to the specific fiber that reflects the component that is rendering at the moment.

alexeyraspopov commented Oct 25, 2018

I'm concerned that these hook functions are provided by the top level react module and imply (or require) global state to work. Ideally, hooks and effects functions could be provided to the functional component when it's executed.

@leebyron, I think, the way how it works, is by using an incapsulated access to the current rendering fiber that holds the state and effects. The API may look like something "global" happens under the hood, but it is still scoped to the specific fiber that reflects the component that is rendering at the moment.

@benjamn

This comment has been minimized.

Show comment
Hide comment
@benjamn

benjamn Oct 25, 2018

@leebyron Alternatively, functional components could be invoked by the React internals with a meaningful this object, containing any number of useful methods.

benjamn commented Oct 25, 2018

@leebyron Alternatively, functional components could be invoked by the React internals with a meaningful this object, containing any number of useful methods.

@david

This comment has been minimized.

Show comment
Hide comment
@david

david Oct 25, 2018

What's the advantage of this approach over a HOC-based one such as the one used, for example, in recompose?

david commented Oct 25, 2018

What's the advantage of this approach over a HOC-based one such as the one used, for example, in recompose?

@sebmarkbage

This comment has been minimized.

Show comment
Hide comment
@sebmarkbage

sebmarkbage Oct 25, 2018

Collaborator

@leebyron Conceptually they’re algebraic effects. It just happens that the engine (a pointer to the current “handler”) lives in the react package. Note that the actual implementation doesn’t live in the react-package. So anyone can implement their own dispatcher. Even inside a react render. If this is a popular pattern you could just have a general purpose pattern for this like “dispatcher” package or something.

Just like context there doesn’t have to be one. In multi-threaded environments there can be several.

We considered passing it but then you would have to pass it through multiple layers of indirection. We already know this to be a pain (which is why we have context to begin with) and for something as light weight as custom hooks it is even more so.

Collaborator

sebmarkbage commented Oct 25, 2018

@leebyron Conceptually they’re algebraic effects. It just happens that the engine (a pointer to the current “handler”) lives in the react package. Note that the actual implementation doesn’t live in the react-package. So anyone can implement their own dispatcher. Even inside a react render. If this is a popular pattern you could just have a general purpose pattern for this like “dispatcher” package or something.

Just like context there doesn’t have to be one. In multi-threaded environments there can be several.

We considered passing it but then you would have to pass it through multiple layers of indirection. We already know this to be a pain (which is why we have context to begin with) and for something as light weight as custom hooks it is even more so.

@jaredLunde

This comment has been minimized.

Show comment
Hide comment

jaredLunde commented Oct 25, 2018

@sebmarkbage

This comment has been minimized.

Show comment
Hide comment
@sebmarkbage

sebmarkbage Oct 25, 2018

Collaborator

@benjamn The this was actually in the first idea and later dropped because it added weirdness and got even weirder when composed with custom hooks. Since they would need to change to a different variable or use .call.

Collaborator

sebmarkbage commented Oct 25, 2018

@benjamn The this was actually in the first idea and later dropped because it added weirdness and got even weirder when composed with custom hooks. Since they would need to change to a different variable or use .call.

@probablyup

This comment has been minimized.

Show comment
Hide comment
@probablyup

probablyup Oct 25, 2018

Are there any concerns about the interaction of transpilers with state hooks? The order of function calls could conceivably be rearranged by a transpiler or minifier in a way that differs between an SSR and client-side bundle.

probablyup commented Oct 25, 2018

Are there any concerns about the interaction of transpilers with state hooks? The order of function calls could conceivably be rearranged by a transpiler or minifier in a way that differs between an SSR and client-side bundle.

@HenriBeck

This comment has been minimized.

Show comment
Hide comment
@HenriBeck

HenriBeck Oct 28, 2018

@Hypnosphi that's great, I checked the docs before I wrote that comment and couldn't find that.
The question would be now on how to cancel the update.

HenriBeck commented Oct 28, 2018

@Hypnosphi that's great, I checked the docs before I wrote that comment and couldn't find that.
The question would be now on how to cancel the update.

@leoyli

This comment has been minimized.

Show comment
Hide comment
@leoyli

leoyli Oct 28, 2018

@HenriBeck can you describe what do you mean by saying "cancel the update"? Do you mean opt-out to perform a side-effect? Or are you talking about time traveling (since side effect is done and you want to reverse this effect)?

leoyli commented Oct 28, 2018

@HenriBeck can you describe what do you mean by saying "cancel the update"? Do you mean opt-out to perform a side-effect? Or are you talking about time traveling (since side effect is done and you want to reverse this effect)?

@brucou

This comment has been minimized.

Show comment
Hide comment
@brucou

brucou Oct 28, 2018

@FredyC

We shouldn't be trying to make solid API that prevents mistakes, but rather to give us great experience when coding with React.

That is a tad controversial. In any case something many, including myself would totally disagree with. Imagine a car manufacturer : 'we shouldn't be trying to make a car which the user can drive safely, but cars that the user enjoys driving. Drivers will make accidents anyways.'. Aside from that, preventing mistakes is part of the great developer experience that you are mentioning. We want both, but if I can't have both, I'll take the first one anytime.

Back on the subject matter of react hooks :

  • the name hooks might not be so bad. It seems to me like real hooks, albeit reverse hooks, because you are not hooking into React but React is hooking into your 'function' (just like join points in aspect-oriented programming).
  • In fact, we have such a concept already which is coroutines, where two routines cooperate towards a common goal. So maybe that could be implemented in a more solid way with generators? With the additional benefit to my eyes that generators are syntactically separated from regular functions, you can have different runners (interpreter) for a generator (say a test interpreter), and you can define combinators on generators (like operators with Rxjs for streams). Of course much more thought would have to be given to that if ever meant to be anything close to a proposal, but my point here is : have we exhausted the safe and reliable ways to do effects within the language?
  • The answer is probably no. The constraint however is to do effects WITHIN React component architecture which is optimized to handle only the view rendering effect. Why not instead of forcing other effects into React by the back door, have them all at the same level, just as the view? what is returned by components now is a React.Element which is a description of the render effect to perform. Why not also return a description of the additional effects to perform? What makes rendering so different from other effects?

This separation of effect handlers and effect description is already used in some architecture such as Cyclejs, and languages with effect systems. That goes just to say that I do not pull that out of the hat. We would keep pure components pure, and in exchange have to add effect handlers somewhere, but all with our standard beloved javascript. Nothing weird that your mama cannot approve of.

brucou commented Oct 28, 2018 •

@FredyC

We shouldn't be trying to make solid API that prevents mistakes, but rather to give us great experience when coding with React.

That is a tad controversial. In any case something many, including myself would totally disagree with. Imagine a car manufacturer : 'we shouldn't be trying to make a car which the user can drive safely, but cars that the user enjoys driving. Drivers will make accidents anyways.'. Aside from that, preventing mistakes is part of the great developer experience that you are mentioning. We want both, but if I can't have both, I'll take the first one anytime.

Back on the subject matter of react hooks :

  • the name hooks might not be so bad. It seems to me like real hooks, albeit reverse hooks, because you are not hooking into React but React is hooking into your 'function' (just like join points in aspect-oriented programming).
  • In fact, we have such a concept already which is coroutines, where two routines cooperate towards a common goal. So maybe that could be implemented in a more solid way with generators? With the additional benefit to my eyes that generators are syntactically separated from regular functions, you can have different runners (interpreter) for a generator (say a test interpreter), and you can define combinators on generators (like operators with Rxjs for streams). Of course much more thought would have to be given to that if ever meant to be anything close to a proposal, but my point here is : have we exhausted the safe and reliable ways to do effects within the language?
  • The answer is probably no. The constraint however is to do effects WITHIN React component architecture which is optimized to handle only the view rendering effect. Why not instead of forcing other effects into React by the back door, have them all at the same level, just as the view? what is returned by components now is a React.Element which is a description of the render effect to perform. Why not also return a description of the additional effects to perform? What makes rendering so different from other effects?

This separation of effect handlers and effect description is already used in some architecture such as Cyclejs, and languages with effect systems. That goes just to say that I do not pull that out of the hat. We would keep pure components pure, and in exchange have to add effect handlers somewhere, but all with our standard beloved javascript. Nothing weird that your mama cannot approve of.

@HenriBeck

This comment has been minimized.

Show comment
Hide comment
@HenriBeck

HenriBeck Oct 28, 2018

By "cancel the update" I mean "canceling the state update". Similar to how setState will not make any state changes when you return null from it.

The reason why this might be important and good for performance is the following:
Check out this code: https://codesandbox.io/s/l29qwjxx0z

We solved the weird but logical behavior from this issue by passing a function to the state updater.
Now a problem if you check the above codesandbox is that you still get a lot of unnecessary rerenders.
I proposed to have a simple equality check to see if the value update so the Developer could cancel the update state by returning the previous value.

HenriBeck commented Oct 28, 2018

By "cancel the update" I mean "canceling the state update". Similar to how setState will not make any state changes when you return null from it.

The reason why this might be important and good for performance is the following:
Check out this code: https://codesandbox.io/s/l29qwjxx0z

We solved the weird but logical behavior from this issue by passing a function to the state updater.
Now a problem if you check the above codesandbox is that you still get a lot of unnecessary rerenders.
I proposed to have a simple equality check to see if the value update so the Developer could cancel the update state by returning the previous value.

@markerikson

This comment has been minimized.

Show comment
Hide comment
@markerikson

markerikson Oct 28, 2018

@HenriBeck , @leoyli : Dan and Sophie told me that's something they want to make sure is added / possible before 16.7 goes final, but no specifics on how yet.

markerikson commented Oct 28, 2018

@HenriBeck , @leoyli : Dan and Sophie told me that's something they want to make sure is added / possible before 16.7 goes final, but no specifics on how yet.

@simon-robertson

This comment has been minimized.

Show comment
Hide comment
@simon-robertson

simon-robertson Oct 28, 2018

Is it possible for multiple function components to observe the same state, and update to reflect changes to that state, using hooks? I believe the current hooks allow this but I can't wrap my head around the wiring at the moment.

import { useGlobalCounter } from 'somewhere';

export const ComponentA = () => {
  const [ counter, increaseCounter ] = useGlobalCounter();

  return <div>{counter}</div>;
};

export const ComponentB = () => {
  const [ counter, increaseCounter ] = useGlobalCounter();

  return <div>{counter}</div>;
};

So, in that example, both ComponentA and ComponentB would display the same counter value regardless of where the increaseCounter function was called from?

simon-robertson commented Oct 28, 2018

Is it possible for multiple function components to observe the same state, and update to reflect changes to that state, using hooks? I believe the current hooks allow this but I can't wrap my head around the wiring at the moment.

import { useGlobalCounter } from 'somewhere';

export const ComponentA = () => {
  const [ counter, increaseCounter ] = useGlobalCounter();

  return <div>{counter}</div>;
};

export const ComponentB = () => {
  const [ counter, increaseCounter ] = useGlobalCounter();

  return <div>{counter}</div>;
};

So, in that example, both ComponentA and ComponentB would display the same counter value regardless of where the increaseCounter function was called from?

@Lokeh

This comment has been minimized.

Show comment
Hide comment
@Lokeh

Lokeh Oct 28, 2018

@simon-robertson you could track the state globally, but would probably be better to bring the state into the React tree and provide it to ComponentA and ComponentB with useContext.

Lokeh commented Oct 28, 2018

@simon-robertson you could track the state globally, but would probably be better to bring the state into the React tree and provide it to ComponentA and ComponentB with useContext.

@satya164

This comment has been minimized.

Show comment
Hide comment
@satya164

satya164 Oct 28, 2018

Member

@simon-robertson same as how you'd do it right now, move the state up to the parent and pass the state value and updater via props/context.

Member

satya164 commented Oct 28, 2018

@simon-robertson same as how you'd do it right now, move the state up to the parent and pass the state value and updater via props/context.

@simon-robertson

This comment has been minimized.

Show comment
Hide comment
@simon-robertson

simon-robertson Oct 28, 2018

Thanks @Lokeh, that is what I was looking for.

simon-robertson commented Oct 28, 2018

Thanks @Lokeh, that is what I was looking for.

@leoyli

This comment has been minimized.

Show comment
Hide comment
@leoyli

leoyli Oct 28, 2018

@simon-robertson and you can abstract them using context API, and use them from useContext so it can be arbitrarily deep.

leoyli commented Oct 28, 2018

@simon-robertson and you can abstract them using context API, and use them from useContext so it can be arbitrarily deep.

@Lokeh

This comment has been minimized.

Show comment
Hide comment
@Lokeh

Lokeh Oct 28, 2018

A lot of people are bringing up lots of concerns about syntax / naming / etc. The most important thing for me is:

  1. How testable is it
  2. How flexible is it

It's been brought up a few times that this feature looks very coupled to the react renderer, and that makes testing and extending the feature very awkward.

It would be really great to, along with this RFC, have a proposal for a way for React libraries to use the API that Hooks use to interact with the renderer. At the very least, provide some blessed tools for us to provide our own dispatcher so that we can easily test our components with hooks. But I think that having a proper API that allows us lower level access to these "memory cells" within the renderer could be an interesting place for libraries to continue to experiment in userland after Hooks settle in to the community.

Lokeh commented Oct 28, 2018 •

A lot of people are bringing up lots of concerns about syntax / naming / etc. The most important thing for me is:

  1. How testable is it
  2. How flexible is it

It's been brought up a few times that this feature looks very coupled to the react renderer, and that makes testing and extending the feature very awkward.

It would be really great to, along with this RFC, have a proposal for a way for React libraries to use the API that Hooks use to interact with the renderer. At the very least, provide some blessed tools for us to provide our own dispatcher so that we can easily test our components with hooks. But I think that having a proper API that allows us lower level access to these "memory cells" within the renderer could be an interesting place for libraries to continue to experiment in userland after Hooks settle in to the community.

@godban

This comment has been minimized.

Show comment
Hide comment
@godban

godban Oct 28, 2018

Since useEffect fires each time... any suggestion how it could replace componentDidMount only effect?

Put it under a condition feels dirty

useEffect(async () => {
    if (!props.data) {
        fetchSomething();
    }
}, [null]);

Passing null feels hacky

useEffect(async () => {
    fetchSomething();
}, [null]);

godban commented Oct 28, 2018

Since useEffect fires each time... any suggestion how it could replace componentDidMount only effect?

Put it under a condition feels dirty

useEffect(async () => {
    if (!props.data) {
        fetchSomething();
    }
}, [null]);

Passing null feels hacky

useEffect(async () => {
    fetchSomething();
}, [null]);
@dtinth

This comment has been minimized.

Show comment
Hide comment
@dtinth

dtinth Oct 28, 2018

@godban Pass an empty array: []

This is mentioned in the docs:

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

dtinth commented Oct 28, 2018

@godban Pass an empty array: []

This is mentioned in the docs:

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

@dtinth

This comment has been minimized.

Show comment
Hide comment
@dtinth

dtinth Oct 28, 2018

@mindplay-dk About your proposal of createState, mentioned in #68 (comment), how would custom hooks be implemented and used? Take Ryan Florence’s example of useMedia custom hook shown in the React Conf 2018 talk for example:

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')

Each useMedia hook involves a state hook to keep track of whether the media query matches or not, and an effect hook to cause the state change when window is resized.

Here, order-dependence really helped in minimizing amount of plumbing code. How might we eliminate order-dependency from the above example without incurring more plumbing code?

dtinth commented Oct 28, 2018 •

@mindplay-dk About your proposal of createState, mentioned in #68 (comment), how would custom hooks be implemented and used? Take Ryan Florence’s example of useMedia custom hook shown in the React Conf 2018 talk for example:

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')

Each useMedia hook involves a state hook to keep track of whether the media query matches or not, and an effect hook to cause the state change when window is resized.

Here, order-dependence really helped in minimizing amount of plumbing code. How might we eliminate order-dependency from the above example without incurring more plumbing code?

@leoyli

This comment has been minimized.

Show comment
Hide comment
@leoyli

leoyli Oct 28, 2018

@dtinth the argument is to remove the order dependency since it is library specific and that violate the common sense that how a language can be used. If you arguing on it increasing plumbing code, yeah, might be since it much more verbose. The problem of that approach is that inevitably increasing the amount of API that React need to expose, thus push its complexity. It might something we need to compromise and try to find out where is the balancing point.

leoyli commented Oct 28, 2018

@dtinth the argument is to remove the order dependency since it is library specific and that violate the common sense that how a language can be used. If you arguing on it increasing plumbing code, yeah, might be since it much more verbose. The problem of that approach is that inevitably increasing the amount of API that React need to expose, thus push its complexity. It might something we need to compromise and try to find out where is the balancing point.

@dtinth

This comment has been minimized.

Show comment
Hide comment
@dtinth

dtinth Oct 28, 2018

@leoyli How would you remove the order dependency from the above example? Let’s discuss with code examples.

dtinth commented Oct 28, 2018

@leoyli How would you remove the order dependency from the above example? Let’s discuss with code examples.

@FredyC

This comment has been minimized.

Show comment
Hide comment
@FredyC

FredyC Oct 28, 2018

I am kinda thinking that using createState should be opt-in. Not everyone cares about order dependency. In a simple cases (I believe these are prevalent) where there is eg. single state value, it would be much more approachable if we can just useState. I don't like the idea of having 50 small components and each would be calling its own createState, it really gets annoying after a while.

I suppose that instead of exporting this global-ish useState, it could be in userland like export const useState = createState(), although that would be just another boilerplate you are copying along the projects and that's annoying to maintain.

FredyC commented Oct 28, 2018 •

I am kinda thinking that using createState should be opt-in. Not everyone cares about order dependency. In a simple cases (I believe these are prevalent) where there is eg. single state value, it would be much more approachable if we can just useState. I don't like the idea of having 50 small components and each would be calling its own createState, it really gets annoying after a while.

I suppose that instead of exporting this global-ish useState, it could be in userland like export const useState = createState(), although that would be just another boilerplate you are copying along the projects and that's annoying to maintain.

@leoyli

This comment has been minimized.

Show comment
Hide comment
@leoyli

leoyli Oct 28, 2018

@dtinth please parse the discussions (e.g.) by yourself. I'm neither the originator, nor its advocator, but I think people have been showing how they want to remove the order dependency and why. And I'm still thinking what would be a better way.

And basically it looks like the code will still remains the same in your given case:

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')
...
}

What would be different is how we are accessing the core API inside useMedia. With createXXX, React can assign a key by a Symbol internally when useXXX is created, rather than track the context by its order of execution. This is consistent with the createRef API.

leoyli commented Oct 28, 2018 •

@dtinth please parse the discussions (e.g.) by yourself. I'm neither the originator, nor its advocator, but I think people have been showing how they want to remove the order dependency and why. And I'm still thinking what would be a better way.

And basically it looks like the code will still remains the same in your given case:

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')
...
}

What would be different is how we are accessing the core API inside useMedia. With createXXX, React can assign a key by a Symbol internally when useXXX is created, rather than track the context by its order of execution. This is consistent with the createRef API.

@pungggi

This comment has been minimized.

Show comment
Hide comment
@pungggi

pungggi Oct 28, 2018

I would prefere this
Language-level syntax state foo = 5;
rather than const [foo, setFoo] = useState(5);

The latter feels so cumbersome.

pungggi commented Oct 28, 2018 •

I would prefere this
Language-level syntax state foo = 5;
rather than const [foo, setFoo] = useState(5);

The latter feels so cumbersome.

@dtinth

This comment has been minimized.

Show comment
Hide comment
@dtinth

dtinth Oct 28, 2018

@leoyli I fail to see how useMedia could be possibly implemented while keeping the App code remain looking the same, without introducing order dependency into either useMedia or into React hooks itself. Can you enlighten me?

Here’s the useMedia custom hook from the talk, for reference.

function useMedia(query) {
  let [matches, setMatches] = useState(window.matchMedia(query).matches)
  useEffect(() => {
    let media = window.matchMedia(query)
    if (media.matches !== matches) {
      setMatches(media.matches)
    }
    let listener = () => setMatches(media.matches)
    media.addListener(listener)
    return () => media.removeListener(listener)
  }, [query])
  return matches
}

To further elaborate on why I think it is not possible without introducing call order dependency:

const useMediaState = createStateHook();
function useMedia(query) {
  // Since we have only single `useMediaState` here,
  // how can `useMedia` distinguish between the first call (small)
  // and the second call (large) so that the hook returns a different value?
  //                          |
  let [matches, setMatches] = useMediaState(window.matchMedia(query).matches)
  ...
  return matches
}

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')

dtinth commented Oct 28, 2018 •

@leoyli I fail to see how useMedia could be possibly implemented while keeping the App code remain looking the same, without introducing order dependency into either useMedia or into React hooks itself. Can you enlighten me?

Here’s the useMedia custom hook from the talk, for reference.

function useMedia(query) {
  let [matches, setMatches] = useState(window.matchMedia(query).matches)
  useEffect(() => {
    let media = window.matchMedia(query)
    if (media.matches !== matches) {
      setMatches(media.matches)
    }
    let listener = () => setMatches(media.matches)
    media.addListener(listener)
    return () => media.removeListener(listener)
  }, [query])
  return matches
}

To further elaborate on why I think it is not possible without introducing call order dependency:

const useMediaState = createStateHook();
function useMedia(query) {
  // Since we have only single `useMediaState` here,
  // how can `useMedia` distinguish between the first call (small)
  // and the second call (large) so that the hook returns a different value?
  //                          |
  let [matches, setMatches] = useMediaState(window.matchMedia(query).matches)
  ...
  return matches
}

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')
@dtinth

This comment has been minimized.

Show comment
Hide comment
@dtinth

dtinth Oct 28, 2018

One disadvantage I found about Hooks, compared to Render Props pattern: According to the 1st Hooks rule, Hooks may only be used at the top level, whereas Render Props can be used in a component’s subtree. See this illustration for a contrived example:

rpvh3

In the above example, if we want to make it so that useContext only re-renders the subtree where the context’s value is actually being used, we had to extract that subtree into its own component. This breaks co-location.

Right now, this can be solved from the user-land, with a helper function that establishes a new context for hooks to execute on, e.g., this way:

function AnonymousHookRenderingContext(props) {
  return props.render()
}
function hooked(f) {
  return <AnonymousHookRenderingContext render={f} />
}

...and used like this:

function Nav() {
  return (
    <NavBar>
      <Logo />
      <NavLink to="/home">Home</NavLink>
      <NavLink to="/about">About</NavLink>
      {hooked(() => {
        const authState = useContext(AuthContext)
        return authState.currentUser ? (
          <UserMenu user={authState.currentUser} />
        ) : (
          <NavLink to="/login">Log in</NavLink>
        )
      })}
    </NavBar>
  )
}

Taking the above idea further, what if React came with the above function built-in, or even let you render a function so that it will establish a new context for hooks?

function Nav() {
  return (
    <NavBar>
      ...
      {() => {
        const authState = useContext(AuthContext)
        return authState.currentUser ? (
          <UserMenu user={authState.currentUser} />
        ) : (
          <NavLink to="/login">Log in</NavLink>
        )
      }}
    </NavBar>
  )
}

This would allow an arbitrary number of states inside a single component, as in this counter example:

function CounterExample() {
  const [counters, setCounters] = useState(1)
  return (
    <div>
      {Array(counters).fill().map((_, i) => (
        <div key={i}>
          {() => {
            const [count, setCount] = useState(0)
            return (
              <div>
                {count}{' '}
                <button onClick={() => setCount(count + 1)}>Click me</button>
              </div>
            )
          }}
        </div>
      ))}
      <button onClick={() => setCounters(counters + 1)}>
        MOAR COUNTER
      </button>
    </div>
  )
}

arbitrary-amount-of-hooks

dtinth commented Oct 28, 2018 •

One disadvantage I found about Hooks, compared to Render Props pattern: According to the 1st Hooks rule, Hooks may only be used at the top level, whereas Render Props can be used in a component’s subtree. See this illustration for a contrived example:

rpvh3

In the above example, if we want to make it so that useContext only re-renders the subtree where the context’s value is actually being used, we had to extract that subtree into its own component. This breaks co-location.

Right now, this can be solved from the user-land, with a helper function that establishes a new context for hooks to execute on, e.g., this way:

function AnonymousHookRenderingContext(props) {
  return props.render()
}
function hooked(f) {
  return <AnonymousHookRenderingContext render={f} />
}

...and used like this:

function Nav() {
  return (
    <NavBar>
      <Logo />
      <NavLink to="/home">Home</NavLink>
      <NavLink to="/about">About</NavLink>
      {hooked(() => {
        const authState = useContext(AuthContext)
        return authState.currentUser ? (
          <UserMenu user={authState.currentUser} />
        ) : (
          <NavLink to="/login">Log in</NavLink>
        )
      })}
    </NavBar>
  )
}

Taking the above idea further, what if React came with the above function built-in, or even let you render a function so that it will establish a new context for hooks?

function Nav() {
  return (
    <NavBar>
      ...
      {() => {
        const authState = useContext(AuthContext)
        return authState.currentUser ? (
          <UserMenu user={authState.currentUser} />
        ) : (
          <NavLink to="/login">Log in</NavLink>
        )
      }}
    </NavBar>
  )
}

This would allow an arbitrary number of states inside a single component, as in this counter example:

function CounterExample() {
  const [counters, setCounters] = useState(1)
  return (
    <div>
      {Array(counters).fill().map((_, i) => (
        <div key={i}>
          {() => {
            const [count, setCount] = useState(0)
            return (
              <div>
                {count}{' '}
                <button onClick={() => setCount(count + 1)}>Click me</button>
              </div>
            )
          }}
        </div>
      ))}
      <button onClick={() => setCounters(counters + 1)}>
        MOAR COUNTER
      </button>
    </div>
  )
}

arbitrary-amount-of-hooks

@simon-robertson

This comment has been minimized.

Show comment
Hide comment
@simon-robertson

simon-robertson Oct 28, 2018

Hi.

I'm not sure if this is a useState bug or a misunderstanding, on my part, of how useState should work.

The following code generally works as expected, but the value only ever reaches 101 even though the components using useContext(Counter) are re-rendered whenever increaseValue() is called.

import React, { createContext, useState } from 'react';

export const Counter = createContext();

export const CounterProvider = (props) => {
  const [ state, setState ] = useState({
    value: 100,

    increaseValue: () => {
      setState({ ...state, value: state.value + 1 });
    }
  });

  return (
    <Counter.Provider value={state}>
      {props.children}
    </Counter.Provider>
  );
};

Can anyone see a problem here, or is this a glitch in the matrix?

simon-robertson commented Oct 28, 2018 •

Hi.

I'm not sure if this is a useState bug or a misunderstanding, on my part, of how useState should work.

The following code generally works as expected, but the value only ever reaches 101 even though the components using useContext(Counter) are re-rendered whenever increaseValue() is called.

import React, { createContext, useState } from 'react';

export const Counter = createContext();

export const CounterProvider = (props) => {
  const [ state, setState ] = useState({
    value: 100,

    increaseValue: () => {
      setState({ ...state, value: state.value + 1 });
    }
  });

  return (
    <Counter.Provider value={state}>
      {props.children}
    </Counter.Provider>
  );
};

Can anyone see a problem here, or is this a glitch in the matrix?

@dtinth

This comment has been minimized.

Show comment
Hide comment
@dtinth

dtinth Oct 28, 2018

@simon-robertson You are copying increaseValue from the previous state into the next state. The function increaseValue from the previous state stays bounded to the state from the 1st render, that’s why it will only ever see state.value as 100. (This has nothing to do with TDZ.)

dtinth commented Oct 28, 2018

@simon-robertson You are copying increaseValue from the previous state into the next state. The function increaseValue from the previous state stays bounded to the state from the 1st render, that’s why it will only ever see state.value as 100. (This has nothing to do with TDZ.)

@simon-robertson

This comment has been minimized.

Show comment
Hide comment
@simon-robertson

simon-robertson Oct 28, 2018

@leoyli, thanks. I guess the solution here would be to move the increaseValue() value into the component function and then merge it into the state object?

Counter.Provider value={{ ...state, increaseValue }}>

Getting used to hooks is going to take a while :)

simon-robertson commented Oct 28, 2018 •

@leoyli, thanks. I guess the solution here would be to move the increaseValue() value into the component function and then merge it into the state object?

Counter.Provider value={{ ...state, increaseValue }}>

Getting used to hooks is going to take a while :)

@leoyli

This comment has been minimized.

Show comment
Hide comment
@leoyli

leoyli Oct 28, 2018

@simon-robertson yeah, @dtinth is right, it is nothing to do with TDZ.

leoyli commented Oct 28, 2018

@simon-robertson yeah, @dtinth is right, it is nothing to do with TDZ.

@dtinth

This comment has been minimized.

Show comment
Hide comment
@dtinth

dtinth Oct 28, 2018

@simon-robertson

You are not alone — few people got tripped up by this fact that functions created inside a function component are bound to the state at the time the function is created. This makes for a potential footgun when the said function is stored into the state or used as event handler... To make the function operate on latest state, one must recreate the function (and store that function inside the state in place of the old function, or update event listeners to point the newly created function.)

This is in contrast to class components, where this.state always refer to the latest state, which makes it possible to create a function once (e.g. at constructor or componentDidMount) and use it throughout the lifetime of the component, knowing that this.state will always refer to the latest state of the component.

Another example: #68 (comment)


You can also use function form of setState. If you pass a function to setState, it will receive the latest state. This allows you to work on latest state rather than the state at the time when the function was created:

  const [state, setState] = useState({
    value: 100,

    increaseValue: () => {
      setState(state => ({ ...state, value: state.value + 1 }));
    }
  });

dtinth commented Oct 28, 2018 •

@simon-robertson

You are not alone — few people got tripped up by this fact that functions created inside a function component are bound to the state at the time the function is created. This makes for a potential footgun when the said function is stored into the state or used as event handler... To make the function operate on latest state, one must recreate the function (and store that function inside the state in place of the old function, or update event listeners to point the newly created function.)

This is in contrast to class components, where this.state always refer to the latest state, which makes it possible to create a function once (e.g. at constructor or componentDidMount) and use it throughout the lifetime of the component, knowing that this.state will always refer to the latest state of the component.

Another example: #68 (comment)


You can also use function form of setState. If you pass a function to setState, it will receive the latest state. This allows you to work on latest state rather than the state at the time when the function was created:

  const [state, setState] = useState({
    value: 100,

    increaseValue: () => {
      setState(state => ({ ...state, value: state.value + 1 }));
    }
  });
@j-f1

This comment has been minimized.

Show comment
Hide comment
@j-f1

j-f1 Oct 28, 2018

@simon-robertson I’d suggest this. Remember, state doesn’t have to be an object.

(click to expand)
import React, { createContext, useState, useCallback } from 'react';

export const Counter = createContext();

export const CounterProvider = (props) => {
  const [value, setValue] = useState(100);
  const increment = useCallback(() => setValue(n => n + 1), []);

  return (
    <Counter.Provider value={{ value, increment }}>
      {props.children}
    </Counter.Provider>
  );
};

j-f1 commented Oct 28, 2018 •

@simon-robertson I’d suggest this. Remember, state doesn’t have to be an object.

(click to expand)
import React, { createContext, useState, useCallback } from 'react';

export const Counter = createContext();

export const CounterProvider = (props) => {
  const [value, setValue] = useState(100);
  const increment = useCallback(() => setValue(n => n + 1), []);

  return (
    <Counter.Provider value={{ value, increment }}>
      {props.children}
    </Counter.Provider>
  );
};
@leoyli

This comment has been minimized.

Show comment
Hide comment
@leoyli

leoyli Oct 28, 2018

@j-f1 If I were right, I remembered from the last year's talk saying we should use function in setState all the time for some reason (I remember is due to the async components). I'm wonder if that is also a preferred way using useState hook.

leoyli commented Oct 28, 2018

@j-f1 If I were right, I remembered from the last year's talk saying we should use function in setState all the time for some reason (I remember is due to the async components). I'm wonder if that is also a preferred way using useState hook.

@leoyli

This comment has been minimized.

Show comment
Hide comment
@leoyli

leoyli Oct 28, 2018

To further elaborate on why I think it is not possible without introducing call order dependency:

const useMediaState = createStateHook();
function useMedia(query) {
  // Since we have only single `useMediaState` here,
  // how can `useMedia` distinguish between the first call (small)
  // and the second call (large) so that the hook returns a different value?

Well, you can't.

  //                          |
  let [matches, setMatches] = useMediaState(window.matchMedia(query).matches)
  ...
  return matches
}

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')

Following the idea from #68 comment by @mindplay-dk. It looks like in such case we inevitably need another API like createCustom:

// to define the implementation of a custom hook:
function mediaHook(query) {
   // we need to encapsulate `createStateHook` API inside custom hook:
   const useMediaState = createStateHook();
   let [matches, setMatches] = useMediaState(window.matchMedia(query).matches)
   ...
   return matches
 }

and use it like:

const useSmallMedia = createCustom(mediaHook)   //  well, I don't like this part
const useLargeMedia = createCustom(mediaHook)   //  they should be encapsulated into `App`

 function App() {
   const small = useSmallMedia('(max-width: 400px)')
   const large = useLargeMedia('(min-width: 800px)')
   ...
 }

I can see this is a bit cumbersome, and we need at least one extra API to bind an uid (or Symbol) internally for allowing React to tract its identity. Basically, if we want to get rid of the call order dependency, it requires us to call something to hydrate the custom hook.


(@FredyC, @dtinth ) The most clean way to eliminate the keystroke is using call order dependency for sure, because React need a reference as a key to access the value in the memory. But it prohibit the possibility to conditionally using hooks.

I think the core team is assuming the amount of hooks is never going to be changed once the component have been mounted so it can rely on its call order as the key; but in this way, it try to use some information only available at run-time... That is why I feel there are something wrong here. (That is also where some people find it is done automagically.)

In a given example by @fendy3002, he is possible to tease React by making sure in all possible execution paths the same hook will be executed, so the code is perfectly functioning while you still can use if to wrap around the hook. The reason using the current hook have to be at the top-level is because it is easily getting buggy (so you need a linter rule to help you identify this anti-pattern).

leoyli commented Oct 28, 2018 •

To further elaborate on why I think it is not possible without introducing call order dependency:

const useMediaState = createStateHook();
function useMedia(query) {
  // Since we have only single `useMediaState` here,
  // how can `useMedia` distinguish between the first call (small)
  // and the second call (large) so that the hook returns a different value?

Well, you can't.

  //                          |
  let [matches, setMatches] = useMediaState(window.matchMedia(query).matches)
  ...
  return matches
}

function App() {
  const small = useMedia('(max-width: 400px)')
  const large = useMedia('(min-width: 800px)')

Following the idea from #68 comment by @mindplay-dk. It looks like in such case we inevitably need another API like createCustom:

// to define the implementation of a custom hook:
function mediaHook(query) {
   // we need to encapsulate `createStateHook` API inside custom hook:
   const useMediaState = createStateHook();
   let [matches, setMatches] = useMediaState(window.matchMedia(query).matches)
   ...
   return matches
 }

and use it like:

const useSmallMedia = createCustom(mediaHook)   //  well, I don't like this part
const useLargeMedia = createCustom(mediaHook)   //  they should be encapsulated into `App`

 function App() {
   const small = useSmallMedia('(max-width: 400px)')
   const large = useLargeMedia('(min-width: 800px)')
   ...
 }

I can see this is a bit cumbersome, and we need at least one extra API to bind an uid (or Symbol) internally for allowing React to tract its identity. Basically, if we want to get rid of the call order dependency, it requires us to call something to hydrate the custom hook.


(@FredyC, @dtinth ) The most clean way to eliminate the keystroke is using call order dependency for sure, because React need a reference as a key to access the value in the memory. But it prohibit the possibility to conditionally using hooks.

I think the core team is assuming the amount of hooks is never going to be changed once the component have been mounted so it can rely on its call order as the key; but in this way, it try to use some information only available at run-time... That is why I feel there are something wrong here. (That is also where some people find it is done automagically.)

In a given example by @fendy3002, he is possible to tease React by making sure in all possible execution paths the same hook will be executed, so the code is perfectly functioning while you still can use if to wrap around the hook. The reason using the current hook have to be at the top-level is because it is easily getting buggy (so you need a linter rule to help you identify this anti-pattern).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment