DEV Community

Martin Stark for Eyevinn Video Dev-Team Blog

Posted on • Updated on

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 the constructor
  • 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 (<></>);
}
Enter fullscreen mode Exit fullscreen mode

As a custom hook:

const runOnceBeforeRender = () => {};

const useBeforeInitialRender = (fn) => {
  useState(fn);
}

const Component = () => {
  useBeforeInitialRender(runOnceBeforeRender);

  return (<></>);
};
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)