useEffect()
TLDR
from this
class User extends React.Component {
state = { user: null }
fetch() {
fetchSomething(this.props.query).then(res => {
this.setState({ user: res.result })
})
}
componentDidMount() {
this.fetch()
}
componentDidUpdate(prevProps) {
if (this.props.query !== prevProps.query) {
if (!this.__isUnMounted) this.fetch()
}
}
componentWillUnmount() {
this.__isUnMounted = true
}
render() {
return this.props.children(this.state.user)
}
}
const AppComponent = ({ query }) => {
return (
<User query={query}>
{user => {
return <p>{JSON.stringify(user)}</p>
}}
</User>
)
}
to this
const useUser = query => {
const [user, setUser] = useState(null)
useEffect(
() => {
let current = true
fetchSomething(query).then(res => {
if (current) setUser(res)
})
return () => {
current = false
}
},
[query]
)
return user
}
const AppHooks = ({ query }) => {
const user = useUser(query)
return <p>{JSON.stringify(user)}</p>
}
also read
more complete post