An Interest In:
Web News this Week
- March 28, 2024
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
- March 23, 2024
- March 22, 2024
The equivalent of componentWillMount using React hooks
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.
Original Link: https://dev.to/video/the-equivalent-of-componentwillmount-using-react-hooks-11em
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To