Middle
Implementa un hook personalizzato di React useSubState, che accetta lo stato completo, la funzione setState e il nome della chiave (campo dell'oggetto), e restituisce una tupla con il valore di questa chiave e la funzione per modificarlo — simile a useState, ma per un campo specifico di un grande oggetto di stato.
sobes.tech AI
Risposta dell'AI
jsx import { useCallback } from 'react';
function useSubState(state, setState, key) { const value = state[key];
const setValue = useCallback( (newValue) => { setState(prevState => ({ ...prevState, [key]: typeof newValue === 'function' ? newValue(prevState[key]) : newValue })); }, [key, setState] );
return [value, setValue]; }
// Использование: // const [subValue, setSubValue] = useSubState(state, setState, 'fieldName');