title: How to persist data externally using useReducer()
body: <p>I have an application that has complex data model so useReducer() is a good candidate to use. Because of this complexity instead I will share the code from React docs instead of my original, and explain what I want to do instead.</p>
  
  <p>Take as an example this code, and imagine I want to save it in a database on server, whenever the change happens.</p>
  
  <pre><code>const initialState = {count: 0};
  
  function reducer(state, action) {
    switch (action.type) {
      case 'increment':
        return {count: state.count + 1};
      case 'decrement':
        return {count: state.count - 1};
      default:
        throw new Error();
    }
  }
  
  function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
      &lt;&gt;
        Count: {state.count}
        &lt;button onClick={() =&gt; dispatch({type: 'decrement'})}&gt;-&lt;/button&gt;
        &lt;button onClick={() =&gt; dispatch({type: 'increment'})}&gt;+&lt;/button&gt;
      &lt;/&gt;
    );
  }
  </code></pre>
  
  <p>In my real world application I have tens of actions that are handled by reducer, and to keep things atomic, I want to call different apis when the  particular action happens. </p>
  
  <p>So in this example I would have and endpoint /api/incrementCounter , and /api/decrementCounter</p>
  
  <p>I'm tempted to place a function as a first line in reducer that will handle the server calls, but it feels very hacky.</p>
  
  <pre><code>const initialState = {count: 0};
  
  function reducer(state, action) {
  
    persistData(state, action); &lt;-- Added
  
    switch (action.type) {
      case 'increment':
        return {count: state.count + 1};
      case 'decrement':
        return {count: state.count - 1};
      default:
        throw new Error();
    }
  }
  
  function persistData(state, action) {  &lt;-- Added
    switch (action.type) {
      case 'increment':
        call("/api/increment");
      case 'decrement':
        call("/api/decrement");
      default:
        throw new Error();
    }
  }
  
  function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
      &lt;&gt;
        Count: {state.count}
        &lt;button onClick={() =&gt; dispatch({type: 'decrement'})}&gt;-&lt;/button&gt;
        &lt;button onClick={() =&gt; dispatch({type: 'increment'})}&gt;+&lt;/button&gt;
      &lt;/&gt;
    );
  }
  </code></pre>
  
  <p>Can you suggest more elegant way of handling this?</p>