Search code examples
reactjsnext.jsreact-statereact-state-management

How to manage function component state in NextJS?


I wanna to access a state variable of component 1 in component 2, they are "brothers" components. How can I do this? Only 1 state variable. I'm using nextjs with styled-components and typescript. Also my project have atomic design structure. I wanna to do something like:

const Component1 = (): ReactElement => {
  const [value, setValue] = useState(false);
  return(
    <div>Component 1 code</div>
  );
}

const ComponentRendered = (): ReactElement => {
  const [value, setValue] = useState(false);
  const [shouldRender, setShouldRender] = useState(false);
  
  const conditionalRendering = (component1Variable) => {
    setShouldRender(component1Variable);
  };

  const component2 = (
    <div>Component 2 code</div>
  )

  return {(shouldRender && component2) || <></>};
}


//index.js

const Index = (): ReactElement => {
  return(
    <div>
      <ComponentRendered />
      <OtherComponents />
    </div>
  );
}

Solution

  • If they are brother components, the state should be managed by the Parent component, and passed as props to them.

    I can't really see in your example where you are using Component1, but it could look something like that:

    const Component1 = ({ value }): ReactElement => {
      return(
        <div>Component 1 code</div>
      );
    }
    
    const ComponentRendered = ({ value }): ReactElement => {
      const [shouldRender, setShouldRender] = useState(false);
      
      const conditionalRendering = (component1Variable) => {
        setShouldRender(component1Variable);
      };
    
      const component2 = (
        <div>Component 2 code</div>
      )
    
      return {(shouldRender && component2) || <></>};
    }
    
    
    //index.js
    
    const Index = (): ReactElement => {
      const [value, setValue] = useState(false);
      return(
        <div>
          <ComponentRendered value={value} />
          <Component1 value={value} />
        </div>
      );
    }