Home > front end >  Is there any alternatives in useState when calling multipleStates?
Is there any alternatives in useState when calling multipleStates?

Time:08-19

So I don't really have a problem but I'm troubling with a lot of codes and I want to reduce it.

So for example I have

import React, { useState } from 'react'

function Source() {

    const [addClockName,setAddClockName] = useState("Add Clock Name")
    const [addTime,setAddTime] = useState("Time")
    const [addMusic,setAddMusic] = useState("Music")
    const [addAlarmlength,setAddAlarmlength] = useState("Alarm length")

    return [
        addClockName,setAddClockName,
        addTime,setAddTime,
        addMusic,setAddMusic,
        addAlarmlength,setAddAlarmlength
    ]
}

export default Source

When I'm importing this it will be something like this in other files

import Source from 'path'

    const [
        addClockName,setAddClockName,
        addTime,setAddTime,
        addMusic,setAddMusic,
        addAlarmlength,setAddAlarmlength
    ] = Source()

    instead like this 
    const { addTime } = Source() 
    
    ...or whatsoever

but what I only want to import is just certain items that I need and I want to avoid recalling the same array of items. Is there any alternatives or just a simpler way to do this?

CodePudding user response:

Don't return an array, return an object. Then you can pick only the properties of the object that you want. Since it's a custom hook, you should also probably prefix it with use.

const useSource = () => {
    // ...
    return {
        addClockName, setAddClockName,
        addTime, setAddTime,
        addMusic, setAddMusic,
        addAlarmlength, setAddAlarmlength
    };

and, for example, if you only want to use the music state:

const {
    addMusic,
    setAddMusic,
} = useSource()

But keep in mind that if you do this, you'll have separate states every time you call useSource, which may not be desirable. If you want to have just one full Source state, call it once, then pass down the result so that children can pick what they want to use, like:

const Parent = () => {
    const sourceObj = useSource();
    // ...
    return <SomeComponent sourceObj={sourceObj}>
}
const SomeComponent = ({ sourceObj }) => {
    const { addMusic, setAddMusic } = sourceObj;
    // ...

CodePudding user response:

Don't worry You can make your own hooks and use it. Example: Make custom hooks

const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [url]);

  return [data];
};

export default useFetch;

and use it:

const Home = () => {
  const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");

  return (
    <>
      {data &&
        data.map((item) => {
          return <p key={item.id}>{item.title}</p>;
        })}
    </>
  );
};

Good luck..

  • Related