This content originally appeared on DEV Community π©βπ»π¨βπ» and was authored by IroncladDev
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:
- 
localStoragekey 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
This content originally appeared on DEV Community π©βπ»π¨βπ» and was authored by IroncladDev
 
	
			IroncladDev | Sciencx (2023-02-09T13:42:24+00:00) Proper State Management π with Jotai π» in 30 seconds π π₯. Retrieved from https://www.scien.cx/2023/02/09/proper-state-management-%f0%9f%9b%a0-with-jotai-%f0%9f%91%bb-in-30-seconds-%f0%9f%95%96-%f0%9f%94%a5/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.
