Use cases for `useInsertionEffect` React hook

WBOY
Release: 2024-08-22 19:14:06
Original
473 people have browsed it

Use cases for `useInsertionEffect` React hook

Intro

Everybody familiar with useEffect hook, sometimes useLayoutEffect is more appropriate.

Not so many people ever used useInsertionEffect, let's explore it.

API for hook is very similar to useEffect, need to add code into setup function, dependencies array and it can return a cleanup function.

React docs give this description.

useInsertionEffect is for CSS-in-JS library authors.

It can be useful for other purposes, mainly to run some code once on component mount, e.g. add event listener to a window.

Use cases

Shiki code highlighter

React.useInsertionEffect(() => { initShiki().then((highlight) => { setHtml(highlight(content)); }); }, [content]);
Copy after login

Event listeners for window

useInsertionEffect(() => { const popCb = () => { const newVal = parse(filterUnknownParamsClient(defaultState)); state.current = newVal }; window.addEventListener(popstateEv, popCb); return () => { window.removeEventListener(popstateEv, popCb); }; }, []);
Copy after login

Some custom subscriptions

useInsertionEffect(() => { const cb = () => { _setState(stateMap.get(stateShape.current) || stateShape.current); }; const unsub = subscribers.add(stateShape.current, cb); return () => { unsub(); }; }, []);
Copy after login

Pros and cons

  • The main benefit of this hook is to run code before component rendered, and before other hooks.
  • You're not supposed to use useState.setState from inside this hook, but it is work, maybe it will change in the future.
  • Refs aren't attached by the time hook run.

The above is the detailed content of Use cases for `useInsertionEffect` React hook. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!