title: Correct way of using useReducer with useContext in React
body: <p>I am a new React developer, implementing global state in my app. Im using useReducer with Context API to cache form search data, but I feel I'm using the reducer wrong, even if it works. I am preparing payload BEFORE calling <strong>dispatchSearchData</strong>, instead of doing it directly inside reducer:</p>
  <pre><code>import React, { createContext, useReducer, useMemo, useEffect } from &quot;react&quot;;
  
  const initialData = {
    from: &quot;&quot;,
    to: &quot;&quot;,
    date_go: &quot;&quot;,
    date_back: &quot;&quot;,
    passengers: &quot;&quot;,
  };
  
  const dataReducer = (searchData, newData) =&gt; {
    if (newData === null) {
      localStorage.removeItem(&quot;currentSearchData&quot;);
      return initialData;
    }
    return { ...searchData, ...newData };
  };
  
  const localData = JSON.parse(localStorage.getItem(&quot;currentSearchData&quot;));
  
  export const SearchDataContext = createContext({});
  
  export const SearchDataProvider = (props) =&gt; {
    const [searchData, dispatchSearchData] = useReducer(dataReducer, localData || initialData);
    const searchDataValue = useMemo(
      () =&gt; ({
        searchData,
        setSearchData,
      }),
      [searchData, setSearchData],
    );
    useEffect(() =&gt; {
      localStorage.setItem(&quot;currentSearchData&quot;, JSON.stringify(searchData));
    }, [searchData]);
  
    return &lt;SearchDataContext.Provider value={searchDataValue}&gt;{props.children}&lt;/SearchDataContext.Provider&gt;;
  };
  </code></pre>
  <p>An example of calling it:</p>
  <pre><code>let search = (e) =&gt; {
      e.preventDefault();
      dispatchSearchData(formData);
      setServiceData(null);
  }
  </code></pre>