how can i set initial value for usestate from redux state using selector in react native?

Viewed 1263

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 Answers

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!!

Related