Home > Software engineering >  Create react custom hook
Create react custom hook

Time:07-03

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>
        )
    }

CodePudding user response:

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();
  };

CodePudding user response:

export function useMyHook(myNumber: number): {
  numberButtonHandler: () => void;
  isClicked: boolean;
} {
    const dispatch = useAppDispatch();
    const [isClicked, setIsClicked] = useState<boolean>(false); // <==

    const numberButtonHandler = () => {
        dispatch(addNumber(myNumber));

        setIsClicked(true); // <==
        setTimeout(() => {
            // <==
            setIsClicked(false); // <==
        }, 100); // <==
    };

    return { numberButtonHandler, isClicked };
}

const MyNumber: FC<MyNumberType> = ({ myNumber }) => {
 const { numberButtonHandler, isClicked } = useMyHook(myNumber)

  return (
      <div
          className={`calc-button number ${isClicked ? 'calc-button--clicked' : ''}`}
          onClick={numberButtonHandler}>
          <p className="number__value">{number}</p>
      </div>
  )
}
  • Related