React教程(八) : 自定义Hook

示例1:useMounted

export const useMounted = () => {
  const isMounted = useRef<boolean>(false);

  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);

  return isMounted;
};
export const LoginForm: FC = () => {
  const isMounted = useMounted();

  return(
    <Button type="submit" disabled={isLoading} >
            Login
    </Button>
  );
};

示例2:useWindowSize

function useWindowSize() {
  // Initialize state with undefined width/height so server and client renders match
  // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
  const [windowSize, setWindowSize] = useState({
    width: undefined,
    height: undefined,
  });

  useEffect(() => {
    // Handler to call on window resize
    function handleResize() {
      // Set window width/height to state
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }
    
    // Add event listener
    window.addEventListener("resize", handleResize);
    
    // Call handler right away so state gets updated with initial window size
    handleResize();
    
    // Remove event listener on cleanup
    return () => window.removeEventListener("resize", handleResize);
  }, []); // Empty array ensures that effect is only run on mount

  return windowSize;
}

完整的代码示例:
https://usehooks.com/useWindowSize/

示例3:useQueryState
append query parameters to URL's query string
简单实现版本:

export const useQueryState = <T>() => {
  const history = useHistory();
  const location = useLocation();
  const [parsedQuery, setParsedQuery] = useState<T>({} as T);

  useEffect(() => {
    const query = queryString.parse(location.search);
    setParsedQuery((query as unknown) as T);
  }, [location.search]);

  const updateQuery = (update: Partial<T>) => {
    const oldQuery = queryString.parse(location.search);
    const newQuery = { ...oldQuery, ...update };

    // skip history update if old and new queries are the same
    if (!_.isEqual(oldQuery, newQuery)) {
      history.push({
        search: queryString.stringify(newQuery)
      });
    }
  };

  return [parsedQuery, updateQuery] as const;
};

完整代码:
https://github.com/992990831/modernization/tree/main/customhook

复杂的实现版本:
https://www.npmjs.com/package/use-query-state
https://github.com/yuanfux/use-query-state/blob/master/src/useQueryState/index.ts

最后,附上收集了多个custom hook的网站地址:https://usehooks.com/

posted @   老胡Andy  阅读(778)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示