Sobes.tech
Middle

Implement a custom React hook useSubState that takes the full state, a setState function, and a key name (object field), and returns a tuple of this field's value and a function to change it — similar to useState, but for a specific field of a large state object.

sobes.tech AI

Answer from 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');

Implement a custom React hook useSubState that takes… - sobes.tech