Logo


Use a Recoil Atom to Share State Between Two React Component


Recoil is a brand new state management library for React developed by Facebook.

In this quick lesson we're going to learn how to add it to a React app and how to use a Recoil atom in order to share state between two React components using useRecoilState hook

To download recoil, run in your terminal


1yarn add recoil or npm add recoil

In recoil atoms represents a piece of state. Atoms are the source of truth in your application state.
Atoms can be used in place of React local component state. If the same atom is used from multiple components, all those components share their state.


1import "./styles.css";
2import { RecoilRoot, atom, useRecoilState } from "recoil";
3const num = atom({
4  key: "numState",
5  default: 0
6});
7function Counter() {
8  const [number, setNumber] = useRecoilState(num);
9  return <button onClick={() => setNumber(number + 1)}>{number}</button>;
10}
11function Display() {
12  const [number] = useRecoilState(num);
13  return <div>{number}</div>;
14}
15export default function App() {
16  return (
17    <>
18      <RecoilRoot>
19        <h1>Counter Compoenet</h1>
20        <Counter />
21        <h1>Display Compoenet</h1>
22
23        <Display />
24      </RecoilRoot>
25      <h1>
26        Recoil
27        <br />
28      </h1>
29    </>
30  );
31}
32


Here is the link of recoil live example which we done so far:
Click here



About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share