5 New Hooks in React 18

What’s new in React 18

On March 29, 2022. Meta (formerly Facebook) released React 18. Lots of new things and improvements have been added to React 18 but in this article, we will be going through the new 5 Hooks:

  • useTransition
  • useDeferredValue
  • useId
  • useSyncExternalStore
  • useInsertionEffect

useTransition

useTransition() is a hook for transition. It returns the transition state and a function to start the transition.

useTransition and startTransition let you mark some state updates as not urgent. Other state updates are considered urgent by default.

const [isPending, startTransition] = useTransition();

A transition is a new concept in React to distinguish between urgent and non-urgent updates.

  • Urgent updates reflect direct interaction, like typing, clicking, pressing, and so on.
  • Transition updates transition the UI from one view to another.

Urgent updates like typing, clicking, or pressing, need immediate response to match our intuitions about how physical objects behave. Otherwise, they feel “wrong”. However, transitions are different because the user doesn’t expect to see every intermediate value on the screen.

function App() {
const [isPending, startTransition] = useTransition();
const [count, setCount] = useState(0);

function handleClick() {
startTransition(() => {
setCount(c => c + 1);
})
}

return (
<div>
{isPending && <Spinner />}
<button onClick={handleClick}>{count}</button>
</div>
);
}

startTransition lets you mark updates in the provided callback as transitions.

useId

useId is a hook for generating unique IDs that are stable across the server and client, while avoiding hydration mismatches.

  • These IDs are stable across the server and client, which avoids hydration mismatches for SSR.
  • These Ids are unique for the entire application. In the case of multi-root applications, createRoot/hydrateRoot has an optional prop, identifierPrefix, which can be used to add a prefix to prevent collisions.
  • These Ids can be appended with prefix and/or suffix to generate multiple unique ids that are used in a component.

For a basic example, pass the id directly to the elements that need it:

function Checkbox() {
const id = useId();
return (
<>
<label htmlFor={id}>Do you like React?</label>
<input id={id} type="checkbox" name="react"/>
</>
);
};

For multiple IDs in the same component, append a suffix using the same id:

function Form() {
const id = useId();
return (
<div>
<label htmlFor={id + '-field1'}>Field 1</label>
<div>
<input id={id + '-field1'} type="text" />
</div>
<label htmlFor={id + '-field2'}>Field 2</label>
<div>
<input id={id + '-field2'} type="text" />
</div>
</div>
);
}

Note: useId is not for generating keys in a list. Keys should be generated from your data.

useSyncExternalStore

useSyncExternalStore is a hook recommended for reading and subscribing from external data sources (stores).

const state = useSyncExternalStore(subscribe, getSnapshot[, getServerSnapshot]);

This method accepts three arguments and returns the value of store:

  • subscribe: function to register a callback that is called whenever the store changes.
  • getSnapshot: a function that returns the current value of the store.
  • getServerSnapshot: a function that returns the snapshot used during server rendering.

you can also subscribe to a specific field:

const selectedField = useSyncExternalStore(
store.subscribe,
() => store.getSnapshot().selectedField,
);

However, the most basic example is simply subscribing to the entire store

const state = useSyncExternalStore(store.subscribe, store.getSnapshot);

useInsertionEffect

useInsertionEffect(didUpdate);

The useInsertionEffectsignature is identical to useEffect.but it fires synchronously before all DOM mutations. Use this to inject styles into the DOM before reading layout in useLayoutEffect. Since this hook is limited in scope, this hook does not have access to refs and cannot schedule updates.

useInsertionEffect should be limited to css-in-js library authors. Prefer useEffect or useLayoutEffect instead.

useDeferredValue

useDeferredValue accepts a value and returns a new copy of the value that will defer to more urgent updates. If the current render is the result of an urgent update, like user input, React will return the previous value and then render the new value after the urgent render has been completed.

const deferredValue = useDeferredValue(value);

useDeferredValue only defers the value that you pass to it. If you want to prevent a child component from re-rendering during an urgent update, you must also memoize that component with React.memo or React.useMemo:

function Typeahead() {
const query = useSearchQuery('');
const deferredQuery = useDeferredValue(query);

// Memoizing tells React to only re-render when deferredQuery changes,
// not when query changes.
const suggestions = useMemo(() =>
<SearchSuggestions query={deferredQuery} />,
[deferredQuery]
);

return (
<>
<SearchInput query={query} />
<Suspense fallback="Loading results...">
{suggestions}
</Suspense>
</>
);
}

Thanks,

I hope this was useful for you and gave you the direction to proceed and start using these hooks. I would love to hear your feedback and comments. If you enjoyed reading this article, support me by clapping and following.


5 New Hooks in React 18 was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Shuaib Khan

What’s new in React 18

On March 29, 2022. Meta (formerly Facebook) released React 18. Lots of new things and improvements have been added to React 18 but in this article, we will be going through the new 5 Hooks:

  • useTransition
  • useDeferredValue
  • useId
  • useSyncExternalStore
  • useInsertionEffect

useTransition

useTransition() is a hook for transition. It returns the transition state and a function to start the transition.

useTransition and startTransition let you mark some state updates as not urgent. Other state updates are considered urgent by default.

const [isPending, startTransition] = useTransition();

A transition is a new concept in React to distinguish between urgent and non-urgent updates.

  • Urgent updates reflect direct interaction, like typing, clicking, pressing, and so on.
  • Transition updates transition the UI from one view to another.

Urgent updates like typing, clicking, or pressing, need immediate response to match our intuitions about how physical objects behave. Otherwise, they feel “wrong”. However, transitions are different because the user doesn’t expect to see every intermediate value on the screen.

function App() {
const [isPending, startTransition] = useTransition();
const [count, setCount] = useState(0);

function handleClick() {
startTransition(() => {
setCount(c => c + 1);
})
}

return (
<div>
{isPending && <Spinner />}
<button onClick={handleClick}>{count}</button>
</div>
);
}

startTransition lets you mark updates in the provided callback as transitions.

useId

useId is a hook for generating unique IDs that are stable across the server and client, while avoiding hydration mismatches.

  • These IDs are stable across the server and client, which avoids hydration mismatches for SSR.
  • These Ids are unique for the entire application. In the case of multi-root applications, createRoot/hydrateRoot has an optional prop, identifierPrefix, which can be used to add a prefix to prevent collisions.
  • These Ids can be appended with prefix and/or suffix to generate multiple unique ids that are used in a component.

For a basic example, pass the id directly to the elements that need it:

function Checkbox() {
const id = useId();
return (
<>
<label htmlFor={id}>Do you like React?</label>
<input id={id} type="checkbox" name="react"/>
</>
);
};

For multiple IDs in the same component, append a suffix using the same id:

function Form() {
const id = useId();
return (
<div>
<label htmlFor={id + '-field1'}>Field 1</label>
<div>
<input id={id + '-field1'} type="text" />
</div>
<label htmlFor={id + '-field2'}>Field 2</label>
<div>
<input id={id + '-field2'} type="text" />
</div>
</div>
);
}

Note: useId is not for generating keys in a list. Keys should be generated from your data.

useSyncExternalStore

useSyncExternalStore is a hook recommended for reading and subscribing from external data sources (stores).

const state = useSyncExternalStore(subscribe, getSnapshot[, getServerSnapshot]);

This method accepts three arguments and returns the value of store:

  • subscribe: function to register a callback that is called whenever the store changes.
  • getSnapshot: a function that returns the current value of the store.
  • getServerSnapshot: a function that returns the snapshot used during server rendering.

you can also subscribe to a specific field:

const selectedField = useSyncExternalStore(
store.subscribe,
() => store.getSnapshot().selectedField,
);

However, the most basic example is simply subscribing to the entire store

const state = useSyncExternalStore(store.subscribe, store.getSnapshot);

useInsertionEffect

useInsertionEffect(didUpdate);

The useInsertionEffectsignature is identical to useEffect.but it fires synchronously before all DOM mutations. Use this to inject styles into the DOM before reading layout in useLayoutEffect. Since this hook is limited in scope, this hook does not have access to refs and cannot schedule updates.

useInsertionEffect should be limited to css-in-js library authors. Prefer useEffect or useLayoutEffect instead.

useDeferredValue

useDeferredValue accepts a value and returns a new copy of the value that will defer to more urgent updates. If the current render is the result of an urgent update, like user input, React will return the previous value and then render the new value after the urgent render has been completed.

const deferredValue = useDeferredValue(value);

useDeferredValue only defers the value that you pass to it. If you want to prevent a child component from re-rendering during an urgent update, you must also memoize that component with React.memo or React.useMemo:

function Typeahead() {
const query = useSearchQuery('');
const deferredQuery = useDeferredValue(query);

// Memoizing tells React to only re-render when deferredQuery changes,
// not when query changes.
const suggestions = useMemo(() =>
<SearchSuggestions query={deferredQuery} />,
[deferredQuery]
);

return (
<>
<SearchInput query={query} />
<Suspense fallback="Loading results...">
{suggestions}
</Suspense>
</>
);
}

Thanks,

I hope this was useful for you and gave you the direction to proceed and start using these hooks. I would love to hear your feedback and comments. If you enjoyed reading this article, support me by clapping and following.


5 New Hooks in React 18 was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Shuaib Khan


Print Share Comment Cite Upload Translate Updates
APA

Shuaib Khan | Sciencx (2022-10-03T17:07:03+00:00) 5 New Hooks in React 18. Retrieved from https://www.scien.cx/2022/10/03/5-new-hooks-in-react-18/

MLA
" » 5 New Hooks in React 18." Shuaib Khan | Sciencx - Monday October 3, 2022, https://www.scien.cx/2022/10/03/5-new-hooks-in-react-18/
HARVARD
Shuaib Khan | Sciencx Monday October 3, 2022 » 5 New Hooks in React 18., viewed ,<https://www.scien.cx/2022/10/03/5-new-hooks-in-react-18/>
VANCOUVER
Shuaib Khan | Sciencx - » 5 New Hooks in React 18. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/10/03/5-new-hooks-in-react-18/
CHICAGO
" » 5 New Hooks in React 18." Shuaib Khan | Sciencx - Accessed . https://www.scien.cx/2022/10/03/5-new-hooks-in-react-18/
IEEE
" » 5 New Hooks in React 18." Shuaib Khan | Sciencx [Online]. Available: https://www.scien.cx/2022/10/03/5-new-hooks-in-react-18/. [Accessed: ]
rf:citation
» 5 New Hooks in React 18 | Shuaib Khan | Sciencx | https://www.scien.cx/2022/10/03/5-new-hooks-in-react-18/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.