Sometimes, we want to set cookies in our React apps.
In this article, we’ll look at how to to set cookies in our React apps.
Set a Cookie in React
To set cookies in our React apps, we can use the react-cookie library.
For instance, we can write:
import React, { useState } from "react";
import { useCookies } from "react-cookie";
export default function App() {
const [cookies, setCookie] = useCookies(["name"]);
const [name, setName] = useState("");
const onChange = (newName) => {
setCookie("name", newName, { path: "/" });
};
return (
<div>
<input
value={name}
onChange={(e) => {
setName(e.target.value);
onChange(e.target.value);
}}
/>
<h1>Hello {cookies?.name}!</h1>
</div>
);
}
We have input to changes the name state when we type in it.
It also calls onChange to change the value of the cookie with key name .
Then we get the cookie’s value with the cookie variable that we destructured from the useCookies hook.
The argument for useCookies is an array of keys of cookies to get.
Conclusion
To set cookies in our React apps, we can use the react-cookie library.