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

Add useCopyWrite and useCopyWriteMemo #63

Closed
wants to merge 1 commit into from

Conversation

davej
Copy link

@davej davej commented Feb 12, 2019

useCopyWrite Hook

Hooks are a new addition in React 16.8. They let you use react-copy-write without using render functions.

Let's write our Avatar component in the previous example using the useCopyWrite hook instead.

const Avatar = () => {
  const [src, avatarTheme] = useCopyWrite([
    state => state.user.avatar.src,
    state => state.theme.avatar
  ]);
  return <img src={src} style={avatarTheme} />;
};

Preventing unnecessary updates with useCopyWrite

There is one notable difference between using the render prop approach (<Consumer />) and using the hook approach (useCopyWrite). Using the render prop will only re-render if selected state changes, however, this is currently not possible with the useCopyWrite hook. You can visit this issue for more information.

There is a workaround however, you can use the useCopyWriteMemo hook. This will use the useMemo hook internally to check for state changes.

const Avatar = () =>
  useCopyWriteMemo(
    [state => state.user.avatar.src, state => state.theme.avatar],
    ([src, avatarTheme]) => <img src={src} style={avatarTheme} />
  );

@davej
Copy link
Author

davej commented Feb 15, 2019

Just used this in a real-world project and it doesn't work if the mutate function is outside of the component because it violates the "Hooks can only be called inside the body of a function component" rule. Docs here.

I'll leave this open just in case anybody has ideas for a fix to this issue but feel free to close.

@janbaykara
Copy link

janbaykara commented Apr 23, 2019

Surely something like this would be better?

  const [localState, setState] = useState()
  useCopyWriteMemo(
   [state => state.user.avatar.src, state => state.theme.avatar],
   setState
  );

  return <div>{JSON.stringify(state)}</div>

@davej davej closed this Mar 7, 2023
@davej davej deleted the feature/hooks branch March 7, 2023 12:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants