Using Cookies with React, Redux and React Router 4

Bonus: Passing Cookies and Redux Actions to Formik handlers

Ross Bulat

--

Cookies, a mechanism for persisting data locally in a browser, can be incorporated into your React project in a matter of minutes. If you have React Router 4 and React Redux installed, some extra prop management is required to get your cookie object arriving at the correct Components.

Let’s go through installing the react-cookie package from npm, before configuring our CookiesProvider, and start using cookies in a project. I will also document how to pass your cookies and Redux actions though a Formik handler (my preferred form management package).

Installation

React Cookie is the standard package for cookie integration, summoning over 40k daily downloads at the time of this writing.

Find it at: https://www.npmjs.com/package/react-cookie

Install it into your React project with npm i react-cookie and we are good to go.

Configuration

react-cookie provides a <CookieProvider> component that you wrap around your root <App> component. This sets a cookies object, and allows us to start using cookies anywhere within this component.

If we also have React Router and Redux installed, your index.js file may look something like this after integrating cookies:

index.js

...
import { CookiesProvider } from 'react-cookie';
let initialStore = {
...
};
const store = createStore(rootReducer, initialStore);ReactDOM.render( <CookiesProvider>
<BrowserRouter>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter>
</CookiesProvider>,
document.getElementById('root'));

Here, the CookiesProvider is wrapping our BrowserRouter and Redux Provider component. Import the component with import { CookiesProvider } from ‘react-cookie’; .

App.js

Now, within App.js (or your root app component), the following configuration is required:

  • Use withCookies() to…

--

--

Ross Bulat

Programmer and Author. @ Parity Technologies, JKRB Investments