Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create react custom hook

Please tell me if I can put this functionality in a hook and if so, how to do it? I have marked "<==" lines that need to be moved to the hook. It’s just adding and removing a class after clicking on an element.

 const Number: FC<Number> = ({ number }) => {
        const dispatch = useAppDispatch()
        const [isClicked, setIsClicked] = useState<boolean>(false) // <==
    
        const numberButtonHandler = () => {
            dispatch(addNumber(number))
    
            setIsClicked(true) // <==
            setTimeout(() => { // <==
                setIsClicked(false) // <==
            }, 100) // <==
        }
    
        return (
            <div
                className={`calc-button number ${isClicked ? 'calc-button--clicked' : ''}`}
                onClick={numberButtonHandler}>
                <p className="number__value">{number}</p>
            </div>
        )
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes, You can create a custom hook which will takeinitalValue and which will return an array of isClicked and a function which will change the state as. Please change the name that looks meaningful to you.

codesandbox demo

function useCustomHook(initialState: boolean): [boolean, () => void] {
  const [isClicked, setIsClicked] = useState<boolean>(initialState);

  const changeState = () => {
    setIsClicked(true);
    setTimeout(() => {
      setIsClicked(false);
    }, 100);
  };

  return [isClicked, changeState];
}

and use it as:

const dispatch = useAppDispatch();
  const [isClicked, changeState] = useCustomHook(false);

  const numberButtonHandler = () => {
    dispatch(addNumber(number));
    changeState();
  };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading