DEV Community

Discussion on: Challenge: Write a useState hook without copying React's

Collapse
 
kiranmantha profile image
Kiran Mantha • Edited

try as below:

const isFunction = value => typeof value === 'function';

function useState(obj) {
  let initialState = obj;
  const reducer = fn => {
    let newState;
    if (isFunction(fn)) {
      newState = fn(initialState);
    } else {
      newState = fn;
    }
    Object.assign(initialState, newState);
  };
  return [initialState, reducer];
}

// Usage
const [state, handler] = useState({ a: 1, b: 2 })
console.log('initial state', state);
handler((prevState) => ({ ...prevState, b: 3 }))
console.log('modified state', state);
handler({b: 5});
console.log('modified state', state);
Enter fullscreen mode Exit fullscreen mode