2021年4月29日星期四

Is it correct to use two different useState hook to store an array and a filtered array for passing to components?

I am currently porting my Pokemon project to React as I just learned the basics of React just a couple of weeks ago and want to see how well I can adapt it. Right now, the way I have my code architectured is to use two different useState hooks, one for the original array fetched from the PokeAPI and is only set once. This original array is also passed into my form object, which filters it according to a few form elements such as a Pokemon type or the Pokemon's name. And another useState hook is used to keep track of the filteredList which is what gets rendered to the website using the Array.map() function.

  const [pokemonList, setPokemonList] = useState([]);    const [filteredList, setPokemonFilteredList] = useState([]);  

Here's the useEffect() hook where we fetch and set the states

  useEffect(() => {      const getPokemon = async () => {        const list = await fetchPokemon();        setPokemonList(list);        setPokemonFilteredList(list);      };  

And finally the pokemonList state variable and setPokemonFilteredList methods get passed into the <PokemonSearchForm>

<PokemonSearchForm pokemonList={pokemonList} setPokemonList={setPokemonFilteredList} />  

So as my question title suggests, is the way I use two different useState() 'correct'? Maybe a different way is for the child component to access pokemonList variable? But I believe this may be an anti-pattern.

https://stackoverflow.com/questions/67327287/is-it-correct-to-use-two-different-usestate-hook-to-store-an-array-and-a-filtere April 30, 2021 at 10:04AM

没有评论:

发表评论