DEV Community

Martin Stark for Eyevinn Video Dev-Team Blog

Posted on • Edited on

5

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay