Joseph
Joseph

Reputation: 13

React useEffect not re-rendering functional component

I am passing an access token into a functional component as props. I need the functional component to re-render when the access token has change. I am using useEffect to setState when said access token has change. It is not re-rendering as expected.

const Panel = (props) => {

  const [accessToken, setAccessToken] = useState('');

  useEffect(() => {
    setAccessToken(props.accessToken)
  }, [props.accessToken])

  return (...)
}

Expected: Panel re-render after props.accessToken changes.

Actual: Panel does not re-render with updated props.accessToken value.

Upvotes: 1

Views: 1884

Answers (1)

ravibagul91
ravibagul91

Reputation: 20755

As per your comment,

accessToken value is defined in the parent component by an api call which sets the token value with "this.accessToken = response.data". Then, <Panel accessToken={this.accessToken} />

Component do not re-render based on local instance variable, in your case this.accessToken.

You need to actually set the token in state, and then pass it to child component.

this.setState({accessToken : response.data})

And then pass it from state,

<Panel accessToken={this.state.accessToken} />

Upvotes: 3

Related Questions