reactjs / reactjs/react.dev

Missing early return in set function example?

Open
#6,336 1 comment 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

Regarding this example

import { useState } from 'react';

export default function CountLabel({ count }) {
  const [prevCount, setPrevCount] = useState(count);
  const [trend, setTrend] = useState(null);
  if (prevCount !== count) {
    setPrevCount(count);
    setTrend(count > prevCount ? 'increasing' : 'decreasing');
//    return; here?
  }
  return (
    <>
      <h1>{count}</h1>
      {trend && <p>The count is {trend}</p>}
    </>
  );
}

It seems to me that the example should include an early return statement after setTrend so React doesn't have to compute a tree that might be discarded immediately because the trend is changed from null to increasing / decreasing

first render

return (
    <>
      <h1>{count}</h1>
    </>
  );

immediate second pass

return (
    <>
      <h1>{count}</h1>
      <p>The count is increasing</p>
    </>
  );

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

Open the linked useState documentation example and compare its current behavior with the proposed early return after setTrend. Check the surrounding explanation and example output before deciding whether the example needs revision; done means the example and its explanation accurately reflect the agreed rendering behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.