Skip to content

Instantly share code, notes, and snippets.

@9paradox
Last active September 24, 2024 12:40
Show Gist options
  • Save 9paradox/992629079ebffb9736675c2730db0a4d to your computer and use it in GitHub Desktop.
Save 9paradox/992629079ebffb9736675c2730db0a4d to your computer and use it in GitHub Desktop.
Easy to use Generic Typescript React custom Hook for Handling multiple inputs and saving state for properties of type or object.
import react, { useState } from "react";
const usePartialState = <T extends Partial<T>>(): [T | {}, (fieldName: string, value: any) => void, (state: T) => void] => {
const [state, setState] = useState<T | {}>({});
const setStateByFiled = (fieldName: string, value: any) => {
setState(_s => {
return {
..._s,
[fieldName]: value,
};
});
}
const setEntireState = (data: T) => {
setState(data);
}
return [
state,
setStateByFiled,
setEntireState
];
}
export default usePartialState;
type MyExample = {
myId: number;
someTitle: string;
};
interface MyExampleState extends Partial<MyExample> { }
const MyComponent: React.FC = () => {
const [exampleState, setExampleStateByFiled, setExampleState] = usePartialState<MyExampleState>();
const clearAll = () => {
setExampleState({});
}
return (
<div>
<p>{exampleState?.myId} | {exampleState?.someTitle}</p>
<button onClick={() => setExampleStateByFiled("myId", 1)}>Change Id</button>
<button onClick={() => setExampleStateByFiled("someTitle", "hey everyone!")}>Change title</button>
<button onClick={clearAll}>Clear all</button>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment