why boolean variable is passed to useState() is always false? React hooks

Viewed 7106

I have a simple functional component and would like to initialize the state with a boolean, depending on the condition. For example:

export default() => {

  const st = useSelector(state => state.body);
  const { type } = st;

  let bool = type === 'test'

  const [ hidden, setHidden ] = useState(bool) //this is always true

}

st is just fetching the state from redux, type will be condition. In some cases type will be test so bool will be true, but when it's initializing the state it's always false.

I do a console.log after the useState and hidden displays false???

I'm not sure what's causing to be false. Am i missing something? I appreciate your help and insights

1 Answers

As you said

st is just fetching the state from redux

This is probably the problem.

Probably in the first render, what you get from the redux isn't the correct value (probably null or undefined), so it sets the default value of the state as false, and then happens a second render where it returns the correct value, but won't reassign it to the state.

The default value of useState will be set only in the first render, and if in the first render it isn't what you want, it won't change, unless you set it.

What you could do is use useEffect hook to reset hidden when type changes

export default () => {

  const st = useSelector(state => state.body);
  const { type } = st;

  let bool = type === 'test';

  const [ hidden, setHidden ] = useState(bool) //this is always true

  // reset hidden if type changes
  useEffect(() => {
      setHidden(type === 'test')
  }, [type])

}
Related