reactjs / reactjs/react.dev

Can the strategy to store information from previous render be used in a custom hook?

Open
#5,393 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

I was reading the strategy in the new beta docs, and was thinking whether it could be used in a custom hook? I tried doing it and it worked, but wanted to know whether it's advised or not.

To explain in code, my question is whether this is OK (same example from React docs but trend logic moved to another hook):

import { useState } from 'react';

const useCountTrend = (count) => {
  const [prevCount, setPrevCount] = useState(count);
  const [trend, setTrend] = useState(null);

  if (prevCount !== count) {
    setPrevCount(count);
    setTrend(count > prevCount ? 'increasing' : 'decreasing');
  }

  return trend;
}

function CountLabel({ count }) {
  const trend = useCountTrend(count);

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

function App() {
  const [count, setCount] = useState(0);
  return (
    <>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
      <button onClick={() => setCount(count - 1)}>
        Decrement
      </button>
      <CountLabel count={count} />
    </>
  );
}

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 with the linked React beta documentation section on storing information from previous renders and review the custom-hook example in this issue. Determine whether the pattern is advised for custom hooks and where that guidance belongs in the documentation. Done means the documentation gives a clear answer supported by the example.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.