use-update-layout-effect
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

useUpdateLayoutEffect version minzipped size downloads build

useUpdateLayoutEffect is a React hook that mimics the behavior of componentDidUpdate in function components.

Install

  • npm install use-update-layout-effect --save or
  • yarn add use-update-layout-effect

Use

You use the useUpdateLayoutEffect the same way you would use the useLayoutEffect hook. Provide an effect callback and a dependency list, and the effect callback will only execute when the dependency list updates.

For a behavior exactly the same as componentDidUpdate, provide an empty ([]) or no (undefined) dependency list.

In the following example, there is no alert when the component mounts; but when the username changes, an alert appears.

import useUpdateLayoutEffect from 'use-update-layout-effect';
 
function MyComponent({ username }) {
  useUpdateLayoutEffect(() => {
    alert(`Now logged in as ${username}!`);
  }, [username]);
 
  return <div>{username}</div>;
}

In the following example, a controlled input is allowed to have an in-flight value until "Apply" is clicked. By using an update layout effect, we override the in-flight value when a new controlled value is provided. This is useful when a controlled value may have more than one controlling component.

import useUpdateLayoutEffect from 'use-update-layout-effect';
 
function MyComponent({ onChange, value }) {
  const [localValue, setLocalValue] = React.useState(value);
 
  useUpdateLayoutEffect(() => {
    setLocalValue(value);
  }, [value]);
 
  return (
    <>
      <input
        onChange={e => {
          setLocalValue(e.target.value);
        }}
        value={localValue}
      />
      <input onClick={onChange} type="submit" value="Apply" />
    </>
  );
}

Sponsor 💗

If you are a fan of this project, you may become a sponsor via GitHub's Sponsors Program.

Readme

Keywords

none

Package Sidebar

Install

npm i use-update-layout-effect

Weekly Downloads

1

Version

1.0.0

License

none

Unpacked Size

6.72 kB

Total Files

6

Last publish

Collaborators

  • charlesstover