useState
A magical hook or an 'Array'?, lets find out.
Let's make a function which will return a useState function.
const React = () => {
return {
useState: () => {},
};
};
Declare a let
variable inside React function, this variable will store our state value.
const React = () => {
let stateValue;
return {
useState: () => {},
};
};
Let's do some quick coding.
const React = () => {
let stateValue;
return {
useState: (initialState) => {
stateValue = stateValue || initialState;
const setState = (newStateValue) => {
stateValue = newStateValue;
};
return [stateValue, setState];
},
};
};
In above code, we are returning an array from useState
in which stateValue
is a variable which will hold our current state value, and setState
is a function this will accept a updated value and set it to stateValue
, this is how the state going to update.
This was the all concept, you can checkout the working code here
Comment below for any sort of question from that code.
Top comments (0)