Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
How to write n selection custom hook (React native hooks)

I am trying to implement a n (which will be defined) selection custom hook in order to use for components such as; text inputs, radio buttons etc.

e.g: You have a selection in a form. Let's say gender selection which you would have 3 options; male, female, I don't prefer to say. For this I just wrote something like this.

import {useCallback, useState} from 'react';

export const useTripleSelection = () => {
  const [value, setValue] = useState(0);
  const toggleZero = useCallback(() => {
    setValue(0);
  }, []);

  const toggleOne = useCallback(() => {
    setValue(1);
  }, []);

  const toggleTwo = useCallback(() => {
    setValue(2);
  }, []);

  return [value, toggleZero, toggleOne, toggleTwo];
};

But the problem is I will need something further for future development, I don't want to be have to write double, triple, quadra selection hook.

Is there a way to implement a N selection hook according to this relation ? Can you help me out ? Thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'm not sure that what you are trying to achieve is a best practice. You'd probably be better off with a state with an enum, like:

export enum TGenderValues {
  male = 'male',
  female = 'female',
  notSelected = 'not_selected',
}

Anyway, you could achieve what you want with

import { useCallback, useState } from 'react';

export const useGetNthSelection = () => {
  const [value, setValue] = useState<number>(0);

  const togglerForNthSelection = useCallback((selectionNumber: number) => {
    return () => {
      setValue(selectionNumber);
    };
  }, []);

  return [value, togglerForNthSelection];
};

const YourComponent = () => {
  const [value, togglerForNthSelection] = useGetNthSelection();
  return (
    <YourInput
      onSelectA={togglerForNthSelection(1)}
      onSelectK={togglerForNthSelection(10)}
    />
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda