Gestion de létat sans redux avec Jotai

Author : Vostfrcc
Publish Date : 2020-12-18 18:28:13


https://zenodo.org/communities/adieu-les-cons-2020-streaming-vf-francais-film-complet/?page=1&size=20

 

The most tedious part when implementing Redux is the amount of boilerplate code that you need to write in order to handle the data flow between components and the Redux store. Redux itself was inspired by Flux, a data flow architecture introduced in 2014.

Since the release of React, we’ve seen a transition from the use of class components into the use of functional components with hooks. No offense to Redux and Flux (they are still awesome) but maybe it’s time to use a new pattern that takes advantage of React’s maturity.

Jotai is a state management library for React that will save you from boilerplate tears with its minimalistic API. And yes, you don’t need to create any actions, reducers, or dispatchers when using Jotai!

The mechanics of Jotai is very similar to React Context and Recoil, but even if you’re not familiar with either concept, this article will get you up to speed very quickly, because Jotai is very simple.
How Jotai works

To get started with Jotai, you need to install the library first:

npm install jotai
# or
yarn add jotai

Jotai replaces local state values in React components with atoms. An atom is simply an object that contains a piece of state. This object will then be passed into Jotai’s useAtom() hook so that your components can consume and update the value it currently stores. You can create an atom by calling the atom function:

import { atom } from 'jotai'

const countAtom = atom(0)
const countryAtom = atom('Japan')

The atoms created above (0 and Japan) are now stored inside Jotai’s Provider , which is a component that you can use to wrap your React components:

import { Provider } from 'jotai'

const Root = () => (
  <Provider>
    <App />
  </Provider>
)

From the example above, all components beneath Provider can now access and update Jotai’s atoms.

You can access the atoms by using the useAtom hook, which will return the atom value and an updater function. Yes, it’s very similar to useState() hook:

import { useAtom } from 'jotai'

function Counter() {
  const [count, setCount] = useAtom(countAtom)
  return (
    <>
      <h1>{count} </h1>
      <button onClick={() => setCount((value) => value + 1)}>one up</button>
    </>
  );

And that’s all to it! You can call the atom from any other components, as long as that component is below the Provider component in the DOM tree.

Compared to a React-Redux application structure, a React-Jotai application has a much more straightforward structure. Here’s what a typical React-Redux structure looks like:
Image for post



Catagory :outdoor-dining