This content originally appeared on DEV Community and was authored by Martin Stark
Given that
- the goal is to execute some code once, before the ui is updated
-
componentWillMount
is deprecated (1, 2, 3), and that the suggested replacement is executing code in theconstructor
- code executed before the return statement of a functional component is implicitly run before rendering it
- the rough equivalent of mounting a class component is the initial call of a functional component
The solution would be
Calling a function in the body of the functional component once. This can potentially be achieved with useState
, useMemo
, or useEffect
, depending on the timing required for the use case.
Since the code needs to run before the initial render is committed to the screen, this disqualifies useEffect
, as “The function passed to useEffect will run after the render is committed to the screen.” 4.
Since we want to guarantee that the code will only run once, this disqualifies useMemo
, as "In the future, React may choose to “forget” some previously memoized values and recalculate them on next render" 5.
useState
supports lazy initial state calculations that are guaranteed to only run once during the initial render, which seems like a good candidate for the job.
Example with useState:
const runOnceBeforeRender = () => {};
const Component = () => {
useState(runOnceBeforeRender);
return (<></>);
}
As a custom hook:
const runOnceBeforeRender = () => {};
const useOnInitialRender = (fn) => {
useState(fn);
}
const Component = () => {
useOnInitialRender(fn);
return (<></>);
};
The runOnceBeforeRender
function can optionally return a state that will be available immediately upon the first render of the function, triggering no re-renders.
See use-once on npm.
This content originally appeared on DEV Community and was authored by Martin Stark
Martin Stark | Sciencx (2021-04-29T12:29:48+00:00) The equivalent of componentWillMount using React hooks. Retrieved from https://www.scien.cx/2021/04/29/the-equivalent-of-componentwillmount-using-react-hooks/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.