airbnb/react-with-styles

Provide a `useStyles` method for using with React Hooks API

mohsen1 opened this issue · 5 comments

I imagine the API should not be too different from the HOC. The README example would look like this:

import React from "react";
import { css, useStyles } from "./useStyles";

function MyComponent() {
  const styles = useStyles(({ color }) => ({
    firstLink: {
      color: color.primary
    },

    secondLink: {
      color: color.secondary
    }
  }));

  return (
    <div>
      <a href="/somewhere" {...css(styles.firstLink)}>
        A link to somewhere
      </a>{" "}
      and{" "}
      <a href="/somewhere-else" {...css(styles.secondLink)}>
        a link to somewhere else
      </a>
    </div>
  );
}

export default MyComponent;

That seems to have some differences; notably, the styles object isn't generated eagerly, as it is now; and it could vary on every render, which could have performance and rendering issues.

You can use withStyles with your SFC right now - hooks are a replacement for lifecycle-based things that would otherwise be class components, they're not a general mechanism for everything :-)

Why do you think a hook is a better approach than the HOC?

I believe the thunk is currently lazily executed.

My main concern with this design is that it much more easily allows props to be used in the styles object, which we explicitly want to avoid (which is maybe what @ljharb meant by "it could vary on every render"?)

Yes, that's what I mean - by requiring it to be passed outside the render path, it can't vary based on props, state, or context.

Closing based on feedback. Styles are not a stateful part of the component so it doesn't make sense to use Hooks API for them.

For anyone landing here good news is that there is a useStyles hook available.
//cc @noratarano