Very often when using a hook on a parent component one of its children will also need to use it. Is it better (performance / readability wise) to pass a function that we get from a hook down to a child component or to get it from scratch?
Here's a demo of what I mean:
import { useTranslation } from "react-i18next";
// Parent component
export default function App() {
const { t: formatMessage } = useTranslation();
return (
<div className="App">
<p>{formatMessage("Welcome to React")}</p>
<MyButton1 text="Click me!" formatMessage={formatMessage} />
<MyButton2 text="Click me!" />
</div>
);
}
// Option 1: pass formatMessage as a prop
const MyButton1 = ({ text, formatMessage }) => {
return <button>{formatMessage(text)}</button>;
};
// Option 2: create a new instance of useTranslation
const MyButton2 = ({ text }) => {
const { t: formatMessage } = useTranslation();
return <button>{formatMessage(text)}</button>;
};
Both components work, but <MyButton1 /> gets the formatMessage function directly from his parent, and <MyButton2 /> creates a new instance. I've seen code bases that use both options. Which one do you think is the best one?