Home > Blockchain >  how to refractor common set state functions in reactjs?
how to refractor common set state functions in reactjs?

Time:02-22

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.

CodePudding user response:

I would suggest you to write a custom hook to reuse component logic, for example this way:



   export const useBooks = () => {
      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 {
      book,
      open,
      handleBookClick,
      handleClose
     }
    }
And then use it in the component as below:
    import {useBooks} from 'hooks/useBook'

    function Saved({ authors, books }: BookProps[]) {
      const {handleBookClick, handleClose, open, book} = useBooks();
  

enter code here

      return ( // some code) 
    }
  • Related