-
Notifications
You must be signed in to change notification settings - Fork 46.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug: component is rendered before it should. #21612
Comments
@jordease, |
@joealden, that's not correct. When const Component1 = () => {
const [state, setState] = useState();
if(state === undefined) setState({title: 'Hello'});
return <Component2 state={state} />
}
const Component2 = ({state}) => {
return <p>{state.title.toString()}</p>
} @jordease, the issue is that calling
If you need to update the state in a descendent component, it has to be in an effect or an event handler. |
@billyjanitsch's comment looks correct. Thanks! Going to close this issue. |
@billyjanitsch thanks for correcting the record! I overlooked that last part of the code comment, and I learnt something new today about React! 😃 |
@billyjanitsch I tried using useEffect to solve this but it didn't work as well. const Component1 = () => {
const [state, setState] = useState();
return <Component2 state={state} setState={setState}/>
}
const Component2 = ({state, setState}) => {
useEffect(()=>{
setState({title: 'Hello'})
},[state])
return <Component3 state={state}/>
}
const Component3 = ({state}) => {
// throws an error
return <p>{state.title.toString()}</p>
} I guess the way to this to would be to update state manually for the same render so something like: if(state === undefined){
state = {...state, title: 'Hello'}
//or directly
state.title = 'Hello'
setState({title: 'Hello'})
} |
@jordease that is because
@jordease I personally wouldn't advise doing this; why can you not just set a default state value in your case? If you really can't set a default value where you define the state, I guess instead of manually mutating const Component1 = () => {
const [state, setState] = useState();
return <Component2 state={state} setState={setState} />;
};
const Component2 = ({ state, setState }) => {
const stateFallback = { title: "Hello" };
useEffect(() => {
if (!state) setState(stateFallback);
}, [state]);
return <Component3 state={state ?? stateFallback} />;
};
const Component3 = ({ state }) => {
return <p>{state.title.toString()}</p>;
}; |
Because in this case Component3 will be rendered 2 times... it is solvable though if I dont use setState() and simply use the default value. Thanks for the help! |
Hi,
I am a bit confused about the example below, where I expect the state to be set before a render.
The text was updated successfully, but these errors were encountered: