useSyncExternalStore
- React commonly uses internal states, but
useSyncExternalStore
comes into play when states are managed by third-party libraries or browser APIs outside React. - This hook allows subscription to external stores, like global state in Redux or data in browser APIs (e.g., localStorage), ensuring components re-render upon changes in the external store.
Import:
import { useSyncExternalStore } from 'react'
Syntax:
const variable_name = useSyncExternalStore(subscribe, getSnapshot, [getServerSnapshot]?)
Example: below is the practical example of useSyncExternalStore hook
Javascript
import React from 'react' ; import ResizableElement from './BatteryStatusIndicator' ; function App() { return ( <div> <ResizableElement /> </div> ); } export default App; |
Javascript
import { useSyncExternalStore } from 'react' export default function ResizableElement() { const subscribe = (listener) => { window.addEventListener( 'resize' , listener) return () => { window.removeEventListener( 'resize' , listener) } } const width = useSyncExternalStore(subscribe, () => window.innerWidth); return ( <div> <p>Size: {width}</p> </div> ) } |
Output:
New Hooks in React 18
React’s state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState
, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state and lifecycle management in functional components, provide a more versatile approach to React development.
There are several built-in hooks in React, today we are going to see new React hooks that are introduced in React 18.
Table of Content
- useId
- useDeferredValue
- useTransition
- useSyncExternalStore
- useInsertionEffect