Skip to content
Advertisement

How to pass state between functional components in a single file

I have two functional components in a single js file. I want to pass state from one to another

    import React, { useState } from 'react';
    
    export function StepTracker(props) {
      const [steps, setSteps] = useState(0);
    
      function increment() {
        setSteps(prevState => prevState + 1);
      }
    
      return (
        <div>
          Today you've taken {steps} steps!
          <br />
          <button onClick={increment}>
            I took another step
          </button>
        </div>
      );
    }

    export function funcName(props){
return(<div>{state}</div<)
}

Advertisement

Answer

You can achieve this by making the other component a child component for the one holding the state.

import React, { useState } from 'react';
import './style.css';

export default function StepTracker() {
  const [steps, setSteps] = useState(0);

  function increment() {
    setSteps((prevState) => prevState + 1);
  }

  return (
    <div>
      <FuncName state={steps} />
      Today you've taken {steps} steps!
      <br />
      <button onClick={increment}>I took another step</button>
    </div>
  );
}

export function FuncName(props) {
  return <div>{props.state}</div>;
}

Another method is to use context. Here’s a guide on the official React documentation.

Advertisement