How to useRecoil in ReactJS
Include dependency in Project
npm install recoil
The updated Dependencies in package.json file will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"recoil": "^0.7.7",
"web-vitals": "^2.1.4"
}
Example: This example implements the above-mentioned approach.
Javascript
// App.js import React, { useState } from 'react' ; import { useRecoilState } from 'recoil' ; import { countState } from './GlobalStateStore' ; import GlobalStateDisplay from './GlobalStateDisplay' ; const App = () => { const [inputValue, setInputValue] = useState( '' ); const [count, setCount] = useRecoilState(countState); const handleInputChange = (e) => { setInputValue(e.target.value); }; const updateGlobalState = () => { const number = parseInt(inputValue); if (!isNaN(number)) { setCount(number); setInputValue( '' ); } }; return ( <div> <input type= "number" value={inputValue} onChange={handleInputChange} /> <button onClick={updateGlobalState}> Update Global State</button> <GlobalStateDisplay /> </div> ); }; export default App; |
Javascript
// GlobalStateDisplay.js import React from 'react' ; import { useRecoilValue } from 'recoil' ; import { countState } from './GlobalStateStore' ; const GlobalStateDisplay = () => { const count = useRecoilValue(countState); const squaredValue = count ** 2; return ( <div> <p>Global State: {count}</p> <p>Square of Global State: {squaredValue}</p> </div> ); }; export default GlobalStateDisplay; |
Javascript
// GlobalStateStore.js import { atom } from 'recoil' ; export const countState = atom({ key: 'countState' , default : 0, }); |
Javascript
/// index.js import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.jsx' import './index.css' import { RecoilRoot } from 'recoil' ; ReactDOM.createRoot(document.getElementById( 'root' )).render( <React.StrictMode> <RecoilRoot> <App /> </RecoilRoot> </React.StrictMode>, ) |
How to manage global state in a React application?
Global state refers to data that is accessible across multiple components in a React application. Unlike the local state, which is confined to a single component, the global state can be accessed and modified from anywhere in the component tree.
In this article, we will explore the following approaches by which we can manage the global state in React.
Table of Content
- Using Redux
- Using MobX
- Using Recoil
- Using Zustand
- Using XState