How to write a useComponent custom hook in React?


I want to create a custom hook useComponent which returns a JSX.Element that will be rendered elsewhere.

I have tried this:

import { useState} from 'react';

const useComponent = () => {

  const [value, setValue] = useState('');

  const c = () => {
    return <>
    <p>Component</p>
    <input value={value} onChane={(e) => setValue(e.target.value)} />
    </>
  }

  return {
    c,
    value,
  }

}


export default function App() {

  const {c: C} = useComponent();

  return (
    <div className="App">
      <C />
    </div>
  );
}

but it does not work. Once I try typing on input, nothing happens.

How can I achieve this ?

I know it might be a bad practice to do such a thing, but the reason I want this is to be able to open a global dialog and pass the c component as children to the <Dialog /> component so I can both render c inside the dialog’s body and also have access to the [value, setValue] state. So my use case would be something like:

const {
  openDialogWithProps
} = useGlobalDialog();

const { c, value } = useComponent();

// somewhere in the code
// onClick={ () => openDialogWithProps( { children: c } ) }

// somewhere else in the same code
// onClick={ () => doSomethingWithTheValue(value) }

and the dialog is rendered inside a DialogProvider somewhere up in the hierarchy.

// Dialog.js

const Dialog = () => {
    const {
       dialogProps: { children }
    } = useGlobalDialog();

    return <SomeDialogComponent>{ children }</SomeDialogComponent>
}

The whole dialog thing is just to explain the reason, it is not meant to be a working example.

Source: React – Stack Overflow

November 20, 2021
Category : News
Tags: react hooks | react-component | react-context | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.