DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Martin Stark for Eyevinn Video Dev-Team Blog

Posted 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 useOnInitialRender = (fn) => {
  useState(fn);
}

const Component = () => {
  useOnInitialRender(fn);

  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)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.