Let's take following example with an inline reducer:
const App = () => {
const [state, dispatch] = React.useReducer(s => {
console.log("reducer invoked with state", s)
return s + 1
}, 0);
return (
<div>
<p>{state}</p>
<button onClick={dispatch}>Increment</button>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<div id="root"></div>
On first click, App
is rendered twice, subsequent clicks cause only one re-render.
I would like to understand above behavior of useReducer
. After having read this answer, some things are still not clear to me.
- Why is a double render triggered only first time for
useReducer
? - Are there additional circumstances to 1.), which cause double rendering for an inline reducer as well?
- When would this inline reducer pattern be not recommended (performance, etc.)? Or is it without flaws?