DEV Community

Cover image for Let's make a primitive useState Hook
Prashant Jha
Prashant Jha

Posted on

Let's make a primitive useState Hook

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: () => {}, 
  };
};
Enter fullscreen mode Exit fullscreen mode

Declare a let variable inside React function, this variable will store our state value.

const React = () => {
  let stateValue;
  return {
    useState: () => {}, 
  };
};
Enter fullscreen mode Exit fullscreen mode

Let's do some quick coding.

const React = () => {
  let stateValue;
  return {
   useState: (initialState) => {
     stateValue = stateValue || initialState;
     const setState = (newStateValue) => {
       stateValue = newStateValue;
     };
     return [stateValue, setState];
    },
  };
};
Enter fullscreen mode Exit fullscreen mode

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.

Oldest comments (0)