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

useToggle #67

Closed
nikasepiskveradze opened this issue Apr 5, 2020 · 2 comments
Closed

useToggle #67

nikasepiskveradze opened this issue Apr 5, 2020 · 2 comments

Comments

@nikasepiskveradze
Copy link
Contributor

This hook is implemented many times by many other developer, but i think for it's simplicity and learning purpose to other developers, we should upload this hook on site.

Basically, what this hook does is that, it takes an parameter with value true or false and toggles that value to opposite.
It's useful when we want to take some action into it's opposite action, for example: show and hide modal, show more/show less text, open/close side menu.

As you see, it has one parameter which only takes boolean value and default argument "false".

In this line we switch current value to it's opposite, useCallback hook returns the memorizes function reference and it's second argument "[]" empty array makes sure that returned function only defined once so it won't cause unnecessary rendering, also when we set the value in setState function we pass callback function to it, because every next value is computed from previous value, which guarantees fact that value will change to it's opposite value

const toggle = useCallback(() => setState(state => !state), []);

import { useCallback, useState } from 'react';

function useToggle(initialState = false) {
  const [state, setState] = useState(initialState);
  const toggle = useCallback(() => setState(state => !state), []);

  return [state, toggle];
}

export default useToggle;
@gragland
Copy link
Contributor

gragland commented Dec 2, 2020

Thanks for sharing this and sorry for responding so late! I think this would be great for usehooks. Would you mind doing a pull request for this with a typescript version as well?

@gragland gragland reopened this Dec 2, 2020
@nikasepiskveradze
Copy link
Contributor Author

Thanks for sharing this and sorry for responding so late! I think this would be great for usehooks. Would you mind doing a pull request for this with a typescript version as well?

Yes sure. I am going to do that as well

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

No branches or pull requests

2 participants