This content originally appeared on DEV Community and was authored by Kiran Mantha
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];
}
const [state, handler] = useState({a: 1, b: 2});
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;
}
}
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)
? 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);
};
handler((prevState) => ({...prevState, b:3}))
console.log('modified state: ', state)
? 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];
}
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 ?
This content originally appeared on DEV Community and was authored by Kiran Mantha
Kiran Mantha | Sciencx (2021-06-08T03:50:18+00:00) useState without React. Retrieved from https://www.scien.cx/2021/06/08/usestate-without-react/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.