I am looking to have something run once when the react app first loads and only the one time. At first, one is inclined to make use of the useEffect
hook:
useEffect(() => {
console.log("Effect hook.");
}, []);
The problem with this approach is that when I put it in my App
ponent, the useEffect
hook runs AFTER mounting. Subsequently, the following will fail because stuff won't be defined when the child ponent renders:
function App() {
let stuff;
// Define the supported configs on mount. This will only run at mount time.
useEffect(() => {
console.log("Effect hook.");
stuff = getSomeStuff();
}, []);
//
console.log("About to return.");
return (
<div>
<ComponentThatNeedsStuff stuff={stuff} />
</div>
);
}
and you will see the following printed:
About to return.
Effect hook.
If you only want the function getSomeStuff
to run once but you need the stuff for child ponents, what is the best way to handle that?
I am looking to have something run once when the react app first loads and only the one time. At first, one is inclined to make use of the useEffect
hook:
useEffect(() => {
console.log("Effect hook.");
}, []);
The problem with this approach is that when I put it in my App
ponent, the useEffect
hook runs AFTER mounting. Subsequently, the following will fail because stuff won't be defined when the child ponent renders:
function App() {
let stuff;
// Define the supported configs on mount. This will only run at mount time.
useEffect(() => {
console.log("Effect hook.");
stuff = getSomeStuff();
}, []);
//
console.log("About to return.");
return (
<div>
<ComponentThatNeedsStuff stuff={stuff} />
</div>
);
}
and you will see the following printed:
About to return.
Effect hook.
If you only want the function getSomeStuff
to run once but you need the stuff for child ponents, what is the best way to handle that?
- Does this answer your question? ponentWillMount for react functional ponent? – Kenny Commented Oct 29, 2022 at 12:47
-
Not quite because I'm using state for other things - it's not clear to me how I would integrate the above. I may change how I do this entirely based on feedback ing in as it seems there are multiple alternatives, but
useMemo
as mentioned below in @Nicholas Tower's answer acplished what I set out to do with this question. – Grant Curell Commented Oct 29, 2022 at 13:06
2 Answers
Reset to default 4Running code before render is usually a sign that you’re going against the grain of how React works.
const App = () => {
const [stuff, setStuff] = useState();
useEffect(() => {
console.log("Effect hook.");
setStuff(getSomeStuff());
}, []);
return (
<div>
{stuff && <ComponentThatNeedsStuff stuff={stuff} />}
</div>
);
}
This sounds like a job for useMemo. It lets you do a calculation during rendering, but then on later renders it can skip the calculation and reuse the previous value:
function App() {
const stuff = useMemo(() => {
return getSomeStuff();
}, []);
return (
<div>
<ComponentThatNeedsStuff stuff={stuff} />
</div>
);
}