DEV Community

loading...

useState without React

kiranmantha profile image Kiran Mantha ・2 min read

useState in react is a wonderful hook which is used to create an initial state and a handler to update it. But is there any way to mimic the same behaviour without using react at all??

let’s try..

From react, the useState returns an array which holds state and a handler. lets create a basic function for this

function useState(obj) {
let initialState = obj;
const reducer = fn => {}
return [initialState, reducer];
}
Enter fullscreen mode Exit fullscreen mode
const [state, handler] = useState({a: 1, b: 2});
Enter fullscreen mode Exit fullscreen mode

Yayyy we done it. Wait what ❗️ my handler is not updating the state. hmmm lets tinker the reducer in useState function. The reducer may accept a function with previous state as argument or it may accept an object. let’s do it

const isFunction = value => typeof value === 'function';
const reducer = fn => {
let newState;
if (isFunction(fn)) {
newState = fn(initialState);
} else {
newState = fn;
}
}
Enter fullscreen mode Exit fullscreen mode

hufff what are you doing up there?? well we created a helper function isFunction to check the argument is a function or not. If it is a function we’re passing inital state to it and assign the function value to newState property. If the argument is not a function then we directly assign it to newState property.

😍 great explanation results please

handler((prevState) => ({...prevState, b:3}))
console.log('modified state: ', state)
Enter fullscreen mode Exit fullscreen mode

😾 boring where are the results? 😕 what are we missing?? ahhh we’re getting new state but not assigning it to initial state in reducer. let’s do it

const reducer = fn => {
let newState;
if (isFunction(fn)) {
newState = fn(initialState);
} else {
newState = fn;
}
Object.assign(initialState, newState);
};
Enter fullscreen mode Exit fullscreen mode
handler((prevState) => ({...prevState, b:3}))
console.log('modified state: ', state)
Enter fullscreen mode Exit fullscreen mode

😍 lovely. Finally we did it. lets see the entire function.

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];
}
Enter fullscreen mode Exit fullscreen mode

That’s it. we finally managed to re-create useState hook without react. But there is one catch in above implementation. It only work for objects 😏. But not a bad start right.

Hope you enjoyed this article. Feel free to improvise it and let me know in comments.

Thankyou 👋

Discussion (0)

Forem Open with the Forem app