I don't know shite about:
Prevent useState initializer reruns
set useState default value only once on initial render
Imagine you have an expensive operation that prefills the initial value of your useState in React. With the default way the function providing your initial value would be executed on each rerender.
Default way of setting state
const [audioURL, setAudioURL] = useState(expensiveOperation());
In this example we're "calculating" the source url for and audio sample in expensiveOperation()
and setting it as the default value of audioURL
.
If this was a truly "expensive operation" it would slow down your application on every rerender.
Setting state as a function
In order to prevent all these reruns of expensiveOperation()
we can initialize useState
with a function instead.
const [audioURL, setAudioURL] = useState(() => expensiveOperation());
Now the expensiveOperation()
is only run once on the initial render. Your application will not be slowed down by subsequent initializations 🥳.