reactjs / reactjs/react.dev

React Hooks docs: add an useContext example where state is updated within a functional component

Open
#1,604 6 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

The React Hooks docs has in the useContext section an example where state is updated within a class component. How is this done within a functional component?

I did this example https://codesandbox.io/s/3vxr57vm7q but I am wondering if it is possible with less DRY, especially in index.js, lines 10-18:

  const [count, setCount] = useState(0)

  return (
    <Context.Provider
      value={{
        count: count,
        setCount: setCount
      }}
    >

With just one state property and one setState function it's ok but imagine you have five of those pairs, then you must repeat every one three times (eg.: count in useState, as key and as property in <Context.Provider />).

Hence, an example would be great and if I did it the right way.

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 useContext section of the React Hooks documentation and compare it with the linked CodeSandbox, especially index.js lines 10-18. Done means the section includes a functional-component example showing how context state is updated and addresses whether the repeated state and setter properties can be simplified.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.