Jotai is a simple, no library for state management in React.js. It works similar to useState Hook, which makes it very easy to use. It is also TypeScript friendly and can be set up in seconds.
Let’s get started and install Jotai first.
yarn add jotai
To be able to use the state in the whole app, we need the provider. Just add it to the index.js as follows:
import { Provider } from "jotai"ReactDOM.render(
<Provider>
<App />
</Provider>,
document.getElementById(‘root’)
);
That is all we need at this point. We can directly start using Jotai by creating an atom. The name, which is chosen appropriately, is the smallest unit in the library — every state has its own atom. To an atom, we also pass our default value for the state directly. Let’s set up a state.
In Jotai, an atom is a single, independent piece of state.
It should be defined outside of the component function. Also, there is the useAtom function, which works similar to hooks. This function also depends on an atom — it gets it as a parameter.
This is the difference to the useState hook. With useState we pass the default value directly, in Jotai, we pass it an atom to useAtom.
We should create the atom outside the component; from inside, we can access it with the useState-like useAtom.
import { useAtom, atom } from “jotai”const inputAtom = atom(“”)function App() {
const [input, setInput] = useAtom(inputAtom)
return (
<>
<p>{input}</p>
<input type=”text” placeholder=”enter something” />
</>
);
}
useAtom strongly reminds of useState. As with useState, the first element is the state itself, because we can output in the DOM, the second element it returns is a function, which gets the new state as a parameter.
#javascript #web-development #react #programming #developer