sajad torkamani

Suppose you had the following component tree and you needed to access <RegisterForm />‘s form values in the <Header /> component.

<Root>
  <Layout>
     <Header />
     <Nav />
     <Main>
       <RegisterForm />
     </Main>
  </Layou>
</Root>

How can you do this?

You can sync the form values with some state that lives higher up in your component tree so that you can access the form values anywhere. React Context or Redux should suffice.

For example, you might have something like this in your <RegisterForm>:

function RegisterForm() {
  const dispatch = useDispatch()

  return (
     <>

       <form>
         <FormEffect onChange={(values) => dispatch(setRegisterFormValues(values)} /> 
         {/* ... */}
       </form>
     </>
  )
}

How you implement something like the <FormEffect /> component isn’t important. The main thing is that you’re able to run a callback function whenever any form values change so that you can sync this with Redux, React Context or your state management approach of choice.

Tagged: React