useSafeState
Introduction
A custom React Hook that ensures the safety of component unmounting.
Play
Usage
import { useState, useEffect } from "react";
import { useSafeState } from "@cannonui/reacthooks";
useState;
const ChildCmp = () => {
const value = 0;
const [safeVal, withSetSafeState] = useSafeState<number>(value);
useEffect(() => {
setTimeout(() => {
withSetSafeState((prev) => prev + 1);
}, 3000);
return () => {};
}, []);
return <div>safe value: {safeVal}</div>;
};
const TestUseSafeState = () => {
const [visible, setVisible] = useState(true);
return (
<div>
<button onClick={() => setVisible(false)}>
click to prevent value update after component unmount
</button>
{visible && <ChildCmp />}
</div>
);
};
export default TestUseSafeState;
Return Value
The hook returns an array containing the safe state value and a function withSetSafeState
to update the state safely.
Parameters
Name | Type | Description |
---|---|---|
value | T | The initial value. |
Features
- Ensures that component unmounting won’t trigger state updates for unmounted components.
- Provides the
withSetSafeState
function to safely update the state.
Example
In this example, we have a child component called ChildCmp
that uses the useSafeState
hook to ensure that state updates won’t be triggered after the component is safely unmounted. The ChildCmp
component tries to update the state after 3 seconds, but since the parent component TestUseSafeState
sets visible
to false
, the ChildCmp
component is already unmounted before the state update.
Use Scenario
The useSafeState
hook is useful in scenarios where you need to ensure that state updates won’t be triggered after the component is unmounted. Often, there are asynchronous operations that may still be running before the component unmounts. If state updates continue to be triggered after unmounting, it can lead to errors or exceptions in the application. By using the useSafeState
hook, you can avoid such situations and improve the overall stability of your application.