Home > Net >  How to force React to use setState with only function?
How to force React to use setState with only function?

Time:02-18

consider the following: [xState, setXState] = useState<boolean>(false)

Setting the state could be used either with: setXState(false) or setXState(() => false))

I want to force the second way so developer would only be able to use functional set state.

I tried ESLINT but seems as there is no such way, so I thought of overriding REACT library types:

I found the type itself in react index.d.ts file:

type SetStateAction = S | ((prevState: S) => S);

So I tried overriding it

@types/react/index.d.ts:

declare namespace React {
    type SetStateAction<S> = (prevState: S) => S;
}

But It didn't help.

Any advice?

** IF it is not clear, I insist on forcing that specific hook. I don't want to create a new hook or use useReducer **

CodePudding user response:

replace all your useState to useReducer, as you said you want to pass function into setState that's what reducer means


also custom hook can make it in typescript

import {useState} from 'react'

function useStateFn<T>(val:T){
  let [v,setV]=useState(val)
  return [v,setV as (fn:(v:T)=>T)=>void]
}

const Comp = ()=>{
  let [x,setX]=useStateFn(1)
  ....
}

CodePudding user response:

You could try creating a custom hook:

import {useState} from "react";

const useFunctionalState = (initialState) => {
   const [state, dispatch] = useState(initialState);
   const customDispatch = (fn) => {
      if(typeof fn !== "function") {
         throw new Error("Cannot update the state. Use a function instead");
      }
      dispatch(fn);
   }
   return [state, customDispatch]
}
  • Related