5

when I try to set initial value from redux state, there is nothing on text component but i can see the value on console

   const Profile = props => {

   const userName = useSelector(userSelector);
   const [name, setName] = useState(userName);
   
   console.log(userName);
   
       return (
           <Text>{name}</Text>

       );
}; 

1 Answers1

7

It won't work this way, as redux is getting its value after the initial render so you need to update your state only after the redux value is updated

If your redux store is a string you can directly use userName in place of name.

Use an useEffect hook and add userName to its dependency array.

useEffect(() => {
  setName(userName);
}, [userName])

Add this inside your react component and it will work!!

PRATIK NAIK
  • 489
  • 3
  • 7
  • 1
    What is the source of this information? I can't find any reference to this. I also never had a problem when using selector as initial data in useState. – jayarjo Nov 17 '22 at 18:53