Skip to main content

useSafeState

This hook is used in the same way as React.useState, expect that calling setState after the component is unmounted has no effect rather than throwing an error.

API

function useSafeState<S>(
initialState?: S | (() => S)
): [
state: S | undefined,
setState: React.Dispatch<React.SetStateAction<S | undefined>>
];

Example

import React from "react";
import { useMount, useSafeState } from "@lilib/hooks";

function Example() {
const [data, setData] = useSafeState<any>();

useMount(() => {
fetch("http://example.com/api/getData").then((response) => {
setData(response.json());
});
});

...
}