reactjs / reactjs/react.dev

React docs on "Building Your Own Hooks"

Open
#2,939 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

Please provide guidance if returning elements (or ()=>elements) from custom hook is a good practice or not.

We have a PageLayout component like the following in our own app:

    <PageLayout
      topBarButtons={..}
      onRender={..}
    />

We want to encapsulate topBarButtons and onRender logic within a custom hook, so that the hook is reusable and shippable without PageLayout. (topBarButtons and onRender will share some state, and useOurHook returns [topBarButtons, onRenderFunc]).

This works fine, if not perfect, for me. But since there are so few custom hook example that returns UI elements (or function that returns UI elements like onRender), the team have doubt about this pattern.

I know the doc has the following statement, but I think this is a very common scenario that deserves a sentence or two in the React docs.

"useYourImagination()
Custom Hooks offer the flexibility of sharing logic that wasn’t possible in React components before. You can write custom Hooks that cover a wide range of use cases like form handling, animation, declarative subscriptions, timers, and probably many more we haven’t considered."

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 "Building Your Own Hooks" documentation page and review its existing guidance and examples about custom Hooks. Add a concise explanation of whether returning elements or functions that return elements is an appropriate pattern, including the shared-state scenario described here; the page should answer the team's question without requiring this issue's application-specific context.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.