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
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());
expensiveOperation() is only run once on the initial render. Your application will not be slowed down by subsequent initializations 🥳.