🔧 Proper State Management 🛠 with Jotai 👻 in 30 seconds 🕖 🔥
Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to
Let's dive into React State Management with Jotai.
Passing down values and dispatchers from a useState hook through props is a dreadful 🤢 process. You can avoid all that with two simple hooks 🪝.
useState + Props
No state management ⚰️
import { useState } from 'react';
const Component = () => {
const [value, setValue] = useState("");
return <div>
<input value={value} setValue={(e) => setValue(e.target.value)} />
<OtherComponent value={value}/>
</div>
}
const OtherComponent = ({ value }) => {
return <div>Value is: {value}</div>
}
Jotai atoms
Like a global useState
🤘
import { atom, useAtom } from 'jotai';
const valueAtom = atom("")
const Component = () => {
const [value, setValue] = useAtom(valueAtom);
return <div>
<input value={value} setValue={(e) => setValue(e.target.value)} />
<OtherComponent />
</div>
}
const OtherComponent = () => {
const [value] = useAtom(valueAtom);
return <div>Value is: {value}</div>
}
That's it ✨! You can even export atoms from a file and access them in different files.
LocalStorage + States
Saving state values to localStorage
is an absolute pain 🗡 in React. Jotai's atomWithStorage hook is an atom
with localStorage binding ⛓.
atomWithStorage
takes two parameters:
-
localStorage
key name 🔑 - Initial value
import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils'
// "inputValue" is the localStorage key, "" is the initial value
const valueAtom = atomWithStorage("inputValue", "")
const Component = () => {
const [value, setValue] = useAtom(valueAtom);
return <div>
<input value={value} setValue={(e) => setValue(e.target.value)} />
</div>
}
That's all there is to it ⚡️!
Thanks for reading! If you have any feedback or comments, let me know!
If you enjoy my content, follow me at @IroncladDev on twitter for more!
Say Hello 👋
🐱 Github • ⠕ Replit • 🌐 Website • ✉️ Email
...
🔧 JOTAI(GLOBAL STATE MANGEMENT)
📈 34.12 Punkte
🔧 Programmierung
🔧 How Jotai Was Born
📈 26.72 Punkte
🔧 Programmierung
🔧 Jotai atomWithStorage
📈 26.72 Punkte
🔧 Programmierung
🔧 Jotai Tips
📈 26.72 Punkte
🔧 Programmierung
🔧 Why I love Jotai
📈 26.72 Punkte
🔧 Programmierung
🔧 Why useSyncExternalStore Is Not Used in Jotai
📈 26.72 Punkte
🔧 Programmierung