React – Passing prop from child to parent to child

  javascript, react-hooks, react-router, reactjs

What I’m trying to do is receive a prop from a child component, to the parent via react-router. From there, I’d like to pass that prop to a different child component (not necessarily a sibling), again via the react-router. The general problem seems to be that the initial-state is what is being passed, despite my efforts.

Starting here: The parent component is receiving props from the child through the router. The prop is then being set as the variable ‘auth’ via the useState hook.

// The below code works correctly and as intended. 'auth' is receive from the child component and set with the useState hook.
const [auth, setAuth] = useState(null)

// Auth is the name of the child component. 'receiveAuth' is the function to receive the prop.
<Route exact path="/"
 render={() => <Auth receiveAuth={username => setAuth(username)} />} />

I’ve confirmed that the prop is being correctly received into the component by doing a console.log.

From here, I would like to pass that prop from the parent into a different child component. Unfortunately, passing the variable ‘auth’ does not work.

// The below code does not work correctly. The value of auth in the child component (home) is null (the initial-state).
<Route path="/home"
 render={() => <Home name={auth} />} />

It seems as though the initial state of ‘auth’ is what’s being passed instead. I’ve tried to use ‘auth’ to create a new variable (using the useEffect hook) and then pass that to the child instead. Unfortunately, the new variable isn’t being set correctly.

// Creating a new variable ('user') to hopefully update and pass to the child instead of 'auth'
const [user, setUser] = useState(null)

useEffect(() => {
     if (auth) {
          console.log(auth) // contains the original correct value, received from the child
          setUser(auth)
          console.log(user) // is null, the useState hook doesn't work as intended here
     }
}, [auth])

How come the ‘setUser’ hook doesn’t work here? Is there a better way to accomplish passing the ‘auth’ variable to that component?

Very grateful for your help in advanced.

Source: Ask Javascript Questions

LEAVE A COMMENT