Search code examples
reactjsreact-hookssetstate

is it good to use following in react hooks or any alternative to update the UI


here is my code i am facing the issue that the UI not reRendering after the state changes

const [, setRand] = useState()
setRand(Math.random())

Solution

  • you cannot use useState as const [, setRand] = useState();

    Here is the description from ReactJs documentation.

    You need to use it like this

    const [random, setRandom] = useState(0);
    //or you can just set random in the beginning like
    const [random, setRandom] = useState(Math.random());
    

    And make sure you are accessing it somewhere on return() method like:

    <p>{ random }</p>