reactjs / reactjs/react.dev

context.md example, when not to use contexts

Open
#3,288 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
11.8k
Forks
7.9k
Avg merge
1d 11h
Merged PRs (30d)
11

Description

I'm sorry if this comes across the wrong way. I understand the concept of contexts. What I don't quite understand is this example when to not use them.

It shows this example

<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>

Being replaced by this

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}

and claims

This inversion of control can make your code cleaner in many cases by reducing the amount of props you need to pass through your application and giving more control to the root components.

My gut reaction was the opposite. The Page component now needs to know details of the NavigationBar (it needs to know what elements/components NagivationBar needs. The Page component seems like it should have zero knowledge of what's in the NavigationBar. It should be passing down some opaque hunk of data and letting NavigationBar deal with it. That it does need to know the details is a strong coupling, not a loose coupling.

Is that a bad example that's trying to illustrated some bigger point but the example is just poorly chosen or am I maybe mis-understanding something?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the context.md section containing the “when not to use contexts” example and its surrounding explanation. Compare the example’s stated inversion-of-control benefit with the coupling concern raised here, then clarify or revise the example so its intended guidance and trade-offs are clear.

Written by the indexing model from the issue text.

Assessment

Tech stack
react
Domain
documentation
Issue type
Documentation
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.