Skip to content
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

React #32

Open
noobling opened this issue Jun 25, 2019 · 0 comments
Open

React #32

noobling opened this issue Jun 25, 2019 · 0 comments

Comments

@noobling
Copy link
Owner

noobling commented Jun 25, 2019

Composition

Containment

function FancyBorder(props) {
  return (
    <div className={'FancyBorder FancyBorder-' + props.color>
       {props.children}
    </div>
  )
}

Context

Used when some data needs to be accessed by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult. Examples include authenticated user, theme, preferred language

The issue of passing unused props to intermediate components in order to pass it down to a lower level component

Instead of this

<Page user={user} avatarSize={avatarSize} />
// ... which renders ...
<PageLayout user={user} avatarSize={avatarSize} />
// ... which renders ...
<NavigationBar user={user} avatarSize={avatarSize} />
// ... which renders ...
<Link href={user.permalink}>
  <Avatar user={user} size={avatarSize} />
</Link>

We can pass an entire component

function Page(props) {
  const user = props.user;
  const userLink = (
    <Link href={user.permalink}>
      <Avatar user={user} size={props.avatarSize} />
    </Link>
  );
  return <PageLayout userLink={userLink} />;
}

// Now, we have:
<Page user={user} avatarSize={avatarSize} />
// ... which renders ...
<PageLayout userLink={...} />
// ... which renders ...
<NavigationBar userLink={...} />
// ... which renders ...
{props.userLink}

Which means we only pass one prop rather than two.

The issue with this is that we are moving complexity higher up the tree making them more complicated and forces lower-level components to be more flexible than you want.

How to use Context

Basically global state

const MyContext = React.createContext(defaultvalue)

<MyContext.Provider value={}>
...
</MyContext.Provider>

class MyClass extends React.Component {
  componentDidMount() {
    let value = this.context;
    /* perform a side-effect at mount using the value of MyContext */
  }
  componentDidUpdate() {
    let value = this.context;
    /* ... */
  }
  componentWillUnmount() {
    let value = this.context;
    /* ... */
  }
  render() {
    let value = this.context;
    /* render something based on the value of MyContext */
  }
}
MyClass.contextType = MyContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant