skip to Main Content

I am trying to create a useCustomState hook which I want to work exactly in the same way as useState hook. I wrote the below code but the setState is not working.

import React from 'react'
import ReactDOM from 'react-dom'

const useCustomState = (initialState) => {
  let value = initialState;
  function setValue(newVal){
    value = newVal
  } 
  return [value, setValue]; 
}

function App() {
  const [state, setState] = useCustomState(3)


  return (
    <>
      <h1>{state}</h1>
      <button onClick={()=>(setState(state+1))}>Increment</button>
    </>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

The state shows as 3.
But button does not change state to 4.
What went wrong in my code?

2

Answers


  1. Here’s the updated code:

    import React, { useState } from 'react';
    import ReactDOM from 'react-dom';
    
    const useCustomState = (initialState) => {
      const [state, setState] = useState(initialState);
    
      const setValue = (newVal) => {
        setState(newVal);
      };
    
      return [state, setValue];
    };
    
    function App() {
      const [state, setState] = useCustomState(3);
    
      return (
        <>
          <h1>{state}</h1>
          <button onClick={() => setState(state + 1)}>Increment</button>
        </>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    
    Login or Signup to reply.
  2. Like other comments have mentioned, you should try to use useState for this purpose unless you have a very specific reason not to. The great thing about useState is that you can set it to represent anything you want. It can represent primitive types, like booleans and integers, or it can even represent an object type or array. In your example, you are trying to use an integer as a state, which is a case where you should use useState rather than trying to make your own custom state.

    If what you are trying to do is create a "custom state" so you can set your state to something outside of a primitive type that might be a bit more complex, refer to this React documentation. The first example here shows the user with a state that uses an object representing form fields. For more complex useState situations, consider using objects or arrays, rather than making a custom hook.

    Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search