1

I was just going through a React project that uses hooks and function based components and came across the following peice of code, basically a component that looks like so:

const App = ({ init, isLoading }) => {
  useEffect(() => {
    init();
  }, []);
  const [isMobile, setisMobile] = useState(null);
  console.log('isMobile');
  console.log(isMobile);
  // Set amount of items to show on slider based on the width of the element
  const changeMobile = () => {
    window.matchMedia('(max-width: 80em)').matches
      ? setisMobile(true)
      : setisMobile(false);
  };

  useEffect(() => {
    changeMobile();
    window.addEventListener('resize', changeMobile);
    return () => window.removeEventListener('resize', changeMobile);
  }, []);

  .........
};

The line of code i am talking about can be seen HERE too.

Usually i am used to seeing props being passed to function based components, but what i see here is very different , also where are these properties being passed from ? I.E. { init, isLoading } ?

Also because if i see how the <App /> component is being called HERE, i don't see any props being passed. So how exactly does this functional component get its parameters ?

2 Answers 2

2

props is an Object and can be destructured. Tha't what's happening.

const Component = ({ init, isLoading }) =>{}

Is short for

const Component = props =>{
    const { init, isLoading } = props
}

You destructuring init and isLoading from props and exposing then in your component's scope

Sign up to request clarification or add additional context in comments.

5 Comments

+1 , i understand destructing is at work here but i don't see anything being passed to <App /> either github.com/fidalgodev/movie-library-react/blob/master/src/…
The parameters have values? Or are undefined
init is a function and isLoading is boolean.
In the repo you linked, isLoading comes mapStateToProps and connect. Ie, it comes from a redux store
@NicholasTower , Makes sense yes thats what i was confused about. :P
1

If you look further down the file, you can see that what the file actually exports is a decorated version of <App />. It's using a higher order component from react-redux which provides the props that you see.

const mapStateToProps = ({ geral }) => {
  return { isLoading: geral.loading };
};

export default connect(
  mapStateToProps,
  { init }
)(App);

react-redux internally uses context to access the redux store, which is where it actually gets the values. It may be helpful to think of React's context as kind of "invisible props" that get passed down to every component that's a child of the <Context.Provider> component, and accessed via <Context.Consumer> or useContext.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.