'how to refractor common set state functions in reactjs?
I have two or more components that shares common function that sets some local states. How do I refractor so that I don't repeat the function.
Code: Component 1:
function Trending({ authors, books }: HomeProps) {
const [open, setOpen] = useState(false);
const [book, setBook] = useState<BookProps | null>(null);
const handleBookClick = (book: BookProps) => {
setBook(book);
setOpen(true);
};
const handleClose = () => {
setOpen(false);
setBook(null);
};
return ( // some code)
}
Component 2:
function Saved({ authors, books }: BookProps[]) {
const [open, setOpen] = useState(false);
const [book, setBook] = useState<BookProps | null>(null);
const handleBookClick = (book: BookProps) => {
setBook(book);
setOpen(true);
};
const handleClose = () => {
setOpen(false);
setBook(null);
};
return ( // some code)
}
I tried exporting the function from on component and calling it in another but it says the setOpen and setBook isn't defined which I dint.
Any good approach to refractor and make the function common.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
