Skip to content

Instantly share code, notes, and snippets.

@chivandikwa
Created June 6, 2019 21:17
Show Gist options
  • Save chivandikwa/97d7545134a23f301f7b8886be60cf08 to your computer and use it in GitHub Desktop.
Save chivandikwa/97d7545134a23f301f7b8886be60cf08 to your computer and use it in GitHub Desktop.
An example of incorrect usage of props to set state in ctor. When component rerenders the ctor will not be run again and any mutations to props will not be reflected in current state.
import React, { useState, useEffect } from "react";
import "./App.css";
const App: React.FC = () => {
const [user, setUser] = useState({ name: "john", email: "john.doe@test.zw" });
useEffect(() => {
setTimeout(() => {
setUser({ name: "jane", email: "jane.doe@test.zw" });
}, 500);
}, []);
return <TestComponent user={user} />;
};
interface IUser {
name: string;
email: string;
}
interface IProps {
readonly user: IUser;
}
interface IState {
readonly userName: string;
}
class TestComponent extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
userName: props.user.name
};
}
public render(): React.ReactElement {
return <div>{this.state.userName}</div>;
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment