@zohodesk/hooks
Version:
Unified Component Library - Hooks
41 lines (40 loc) • 1.2 kB
JavaScript
import React, { useCallback, useEffect } from 'react';
import useCommonReducer from "../utils/useCommonReducer";
import tabReducer from "./tabReducer";
import { CHANGETAB } from "./constants";
/**
* Inspired from https://react-spectrum.adobe.com/react-stately/index.html
* Common state management
* this hook is used for easily manage the controller and uncontrolled the selections of form component.
* We can use it for Radio, DropDown, Tab components
* props name should be defaultTab,selectedTab.
* @param {*} props = defaultTab,selectedTab
*/
export default function useSelectTab(props) {
let customReducer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
const {
defaultTab = null,
selectedTab = null
} = props;
const {
state,
dispatch
} = useCommonReducer(tabReducer, customReducer, {
selectedTab: defaultTab || selectedTab
});
const handleChange = useCallback(newTab => {
dispatch({
type: CHANGETAB,
data: newTab
});
}, []);
useEffect(() => {
if (!!selectedTab) {
handleChange(selectedTab);
}
}, [selectedTab]);
return {
selectedTab: state.selectedTab,
handleChange
};
}