What are the considerations behind deciding between passing the out of the box setWhatever
from useState()
down to a child (see case one below) versus creating a custom handleWhatever
function to pass to the child, where the handleWhatever
function uses setWhatever
within it (see case two below)?
Definitely React is about passing state down from parent to child. But after reiterating that fact, it seems like we are always left with countless examples where a function is passed from parent to child for the purpose of keeping a parent aware of a certain value within the child. My question is about such cases where a function needs to be passed down to a child. (If all such cases are misguided and functions being passed down for the sake of updating a parent is an anti-pattern then it would be useful to know what to do instead-- global variable?).
Case #1
// Test.js (parent, case one)
import React, { useState } from 'react';
import DetermineValue from './DetermineValue';
const Test = () => {
const [importantValue, setImportantValue] = useState();
console.log(importantValue);
return <DetermineValue setImportantValue={setImportantValue} />;
};
export default Test;
// DetermineValue.js (child, case one)
import React from 'react';
const DetermineValue = ({ setImportantValue }) => {
return (
<>
...
onClick={() => {
setImportantValue('Important Data');
}}
...
</>
);
};
export default DetermineValue;
Case #2
// Test.js (parent, case two)
import React, { useState } from 'react';
import DetermineValue from './DetermineValue';
const Test = () => {
const [importantValue, setImportantValue] = useState();
const handleSetImportantValue = (importantValueQuickPass) => {
setImportantValue(importantValueQuickPass);
};
console.log(importantValue);
return <DetermineValue handleSetImportantValue={handleSetImportantValue} />;
};
export default Test;
// DetermineValue.js (child, case two)
import React from 'react';
const DetermineValue = ({ handleSetImportantValue }) => {
return (
<>
...
onClick={() => {
handleSetImportantValue('Important Data');
}}
...
</>
);
};
export default DetermineValue;
setImportantValue
function down to a child component is perfectly valid, however, what's bothering me in your code samples is that you seem to call this function during rendering instead of when an action occurs (i.e. button pressed, form submitted etc). P.S. your code sample #2 is merely a wrapper aroundsetImportantValue
- unless there is more logic, I would never do it this wayhandleSetImportantValue
from the parent function really does make "things" different from having only the bare "set" function to work with. Thanks for the quick response! :)