Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add useComponentWillReceiveUpdate #24

Merged
merged 10 commits into from
Oct 11, 2024
Merged

Conversation

Jack-Works
Copy link
Contributor

@Jack-Works Jack-Works commented Oct 10, 2024

useComponentWillReceiveUpdate

Reset part of states when props changed.

Usage

import { useComponentWillReceiveUpdate } from 'foxact/use-abortable-effect';

function Component(props) {
  const [a, setA] = useState('')
  const [b, setB] = useState('')
  // when props.x changed, only reset a, not b
  useComponentWillReceiveUpdate(() => {
    setA('')
  }, [props.x]);
}

If you're using useEffect like this:

  const [state, setState] = useState(false)
  useEffect(() => setState(false), [props.someProp])

Don't do it. See Adjusting some state when a prop changes
It should be like this:

  const [prev, setPrev] = useState(state)
  if (prev !== state) {
    setPrev(state)
    setState(false)
  }

This hook is a helper for the above pattern.

useComponentWillReceiveUpdate(() => setState(false), [state])

This only applies to states of the current component.
Modifying states from other components causes React reporting errors.
You may also want to read (Avoid) Notifying parent components about state changes
and (Avoid) Passing data to the parent.
If you really need to edit other components' states, write it like this:

useComponentWillReceiveUpdate(() => {
  setLocalState(false)
  Promise.resolve().then(() => props.setParentState(false))
}, [state])

Copy link
Owner

@SukkaW SukkaW left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also mention the name of this hook comes from React Class Component: https://react.dev/reference/react/Component#unsafe_componentwillreceiveprops

docs/src/pages/use-component-will-receive-update.mdx Outdated Show resolved Hide resolved
@SukkaW SukkaW merged commit ce72368 into SukkaW:master Oct 11, 2024
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants