Using Cookies with React, Redux and React Router 4
Bonus: Passing Cookies and Redux Actions to Formik handlers
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.