GWorking
GWorking

Reputation: 4341

How to return a component and a function, or what's the alternative?

[React] What is the "way" to send/share a function between components?

Better explained in (useless) code

import React, { useState } from "react";


export default function App() {
  const [bookmarks, setBookmarks] = useState();
  const letbook = () => setBookmarks("hello");

  const Card = () => <div onClick={letbook}>hey</div>;

  const MyCom = () => {
    return <div><Card /></div>;
  };

  return (
    <div className="App">
      <h1 onClick={letbook}>Hello CodeSandbox</h1>
      <MyCom />
      <div>{bookmarks}</div>
    </div>
  );
}
import React, { useState } from "react";

export default function App() {
  const Card = () => <div onClick={letbook}>hey</div>;

  return (
    <div className="App">
      <h1 onClick={letbook}>Hello CodeSandbox</h1>
      <MyCom />
      <div>{bookmarks}</div>
    </div>
  );
}

const MyCom = () => {
  const [bookmarks, setBookmarks] = useState();
  const letbook = () => setBookmarks("hello");

  return (
    <div>
      <Card />
    </div>
  );
};

const [letbook, MyCom] = useMyCom

But this is not recommended (https://www.reddit.com/r/reactjs/comments/9yq1l8/how_do_you_feel_about_a_hook_returning_components/)

Unless (and this is the question) whether there is a smarter way to do this

import React, { useState } from "react";

export default function App() {
  const [bookmarks, setBookmarks, letbook] = useMyCom();

  return (
    <div className="App">
      <h1 onClick={letbook}>Hello CodeSandbox</h1>
      <MyCom card={props => <Card letbook={letbook} />} />
      <div>{bookmarks}</div>
    </div>
  );
}

const Card = ({letbook}) => <div onClick={letbook}>hey</div>;

const useMyCom = () => {
  const [bookmarks, setBookmarks] = useState();
  const letbook = () => setBookmarks("hello");
  return [bookmarks, setBookmarks, letbook];
};

const MyCom = ({ letbook, card }) => <div>{card(letbook)}</div>;

Upvotes: 0

Views: 47

Answers (1)

Gaspar Teixeira
Gaspar Teixeira

Reputation: 1267

Split your component to reuse it is definitely a good idea. But make sure your are using and manipulate a single state in the same file an pass it as props. Also, it is important that you avoid to re-render your child component. Only when your main component change props that are necessary to re-render your child component.

import React, { useState, memo } from "react";

const MyCom = memo(props => {
  return <div>{props.bookmarks}</div>;
});

export default function App() {
  const [bookmarks, setBookmarks] = useState();
  const letbook = () => setBookmarks("hello");

  return (
    <div className="App">
      <h1 onClick={letbook}>Hello CodeSandbox</h1>
      <MyCom bookmarks={bookmarks} />
    </div>
  );
}

Upvotes: 1

Related Questions