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

Adding example for react using hooks #159

Merged
merged 2 commits into from
Dec 14, 2019
Merged

Adding example for react using hooks #159

merged 2 commits into from
Dec 14, 2019

Conversation

nahumzs
Copy link
Contributor

@nahumzs nahumzs commented Dec 14, 2019

This helps to understand how to use nanoid with react hooks.

This helps to understand how to use nanoid in react with hooks.
@ai
Copy link
Owner

ai commented Dec 14, 2019

Am I right, that nanoid() will be called on every component render? I could be bad for performance.

What do you think about this way to use Nano ID with hooks?

const key = useMemo(nanoid)

@TrySound
Copy link

@ai in this case nanoid is called on every render too unless you specify dependencies list. And still useMemo is not stable. It works only for pure computations. React may drop cache any time. These are ways to go.

const useNanoid = () => {
  const ref = React.useRef(null)
  if (ref.current == null) {
    ref.current = nanoid();
  }
  return ref.current;
}

const Component = () => {
  const id = useNanoid()
}
const Component = () => {
  const [id] = React.useState(() => nanoid());
}

@nahumzs
Copy link
Contributor Author

nahumzs commented Dec 14, 2019

I put a small example on place https://codesandbox.io/s/nanoid-with-hooks-yv1u5

@TrySound
Copy link

Did you save it? I don't see any nanoid usage.

@nahumzs
Copy link
Contributor Author

nahumzs commented Dec 14, 2019

@TrySound sorry my bad is there now.

@ai
Copy link
Owner

ai commented Dec 14, 2019

@nahumzs OK, seems like useMemo doesn't work. What do you think about const [id] = useState(nanoid)?

@TrySound
Copy link

useMemo(() => nanoid(), []) does work but eventually may break because nanoid is not pure computation.

@nahumzs
Copy link
Contributor Author

nahumzs commented Dec 14, 2019

const id = React.useState(() => nanoid()) and const [idState] = React.useState(nanoid) would do the work I think is down to what flavor do you prefer I'm ok with both.

@ai
Copy link
Owner

ai commented Dec 14, 2019

ref has a problem with calling Nano ID on every component render. It didn't change the ID, but use CPU.

@ai ai merged commit 1ec3aa9 into ai:master Dec 14, 2019
@ai
Copy link
Owner

ai commented Dec 14, 2019

Thanks for improving docs :)

@nahumzs nahumzs mentioned this pull request Feb 24, 2020
8 tasks
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.

3 participants